Fix refresh token API call not working

This commit is contained in:
Reimar 2024-09-02 13:14:13 +02:00
parent 4b5c74d824
commit 61586ef169
Signed by: Reimar
GPG Key ID: 93549FA07F0AE268
9 changed files with 36 additions and 23 deletions

View File

@ -34,7 +34,10 @@ namespace API.Application.Users.Commands
} }
var jwtToken = _tokenHelper.GenerateJwtToken(user); var jwtToken = _tokenHelper.GenerateJwtToken(user);
return new OkObjectResult(new { token = jwtToken, id = user.Id, refreshToken = user.RefreshToken}); user.RefreshToken = System.Guid.NewGuid().ToString();
_repository.Save();
return new OkObjectResult(new { token = jwtToken, id = user.Id, refreshToken = user.RefreshToken });
} }
} }

View File

@ -61,12 +61,10 @@ namespace API.Controllers
return await _queryAllUsers.Handle(); return await _queryAllUsers.Handle();
} }
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<ActionResult<UserDTO>> GetUser(string id) public async Task<ActionResult<UserDTO>> GetUser(string id)
{ {
return await _queryUserById.Handle(id); return await _queryUserById.Handle(id);
} }
[Authorize] [Authorize]
@ -95,6 +93,5 @@ namespace API.Controllers
User user = await _repository.QueryUserByRefreshTokenAsync(refreshTokenDTO.RefreshToken); User user = await _repository.QueryUserByRefreshTokenAsync(refreshTokenDTO.RefreshToken);
return new OkObjectResult(_tokenHelper.GenerateJwtToken(user)); return new OkObjectResult(_tokenHelper.GenerateJwtToken(user));
} }
} }
} }

View File

@ -11,5 +11,6 @@ namespace API.Persistence.Repositories
Task<User> QueryUserByEmailAsync(string email); Task<User> QueryUserByEmailAsync(string email);
Task<bool> UpdateUserAsync(User user); Task<bool> UpdateUserAsync(User user);
Task<User> QueryUserByRefreshTokenAsync(string refreshToken); Task<User> QueryUserByRefreshTokenAsync(string refreshToken);
void Save();
} }
} }

View File

@ -78,5 +78,10 @@ namespace API.Persistence.Repositories
{ {
return await _context.Users.SingleOrDefaultAsync(u => u.RefreshToken == refreshToken); return await _context.Users.SingleOrDefaultAsync(u => u.RefreshToken == refreshToken);
} }
public void Save()
{
_context.SaveChanges();
}
} }
} }

View File

@ -51,7 +51,7 @@ Future<String?> request(BuildContext? context, ApiService service, String method
if (response.statusCode < 200 || response.statusCode >= 300) { if (response.statusCode < 200 || response.statusCode >= 300) {
try { try {
final json = jsonDecode(response.body); final json = jsonDecode(response.body);
messenger?.showSnackBar(SnackBar(content: Text(json['message']))); messenger?.showSnackBar(SnackBar(content: Text(json['message'] ?? json['title'])));
debugPrint('API error: ' + json['message']); debugPrint('API error: ' + json['message']);
} catch (e) { } catch (e) {
debugPrint(e.toString()); debugPrint(e.toString());
@ -69,7 +69,7 @@ Future<bool> isLoggedIn(BuildContext context) async {
final token = prefs.getString('token'); final token = prefs.getString('token');
if (token == null) { if (token == null) {
prefs.remove('id'); logout();
return false; return false;
} }
@ -81,15 +81,25 @@ Future<bool> isLoggedIn(BuildContext context) async {
if (payload['exp'] < DateTime.now().millisecondsSinceEpoch / 1000) { if (payload['exp'] < DateTime.now().millisecondsSinceEpoch / 1000) {
messenger.showSnackBar(const SnackBar(content: Text('Token expired, please sign in again'))); messenger.showSnackBar(const SnackBar(content: Text('Token expired, please sign in again')));
prefs.remove('token');
logout();
return false; return false;
} }
} catch (e) { } catch (e) {
messenger.showSnackBar(const SnackBar(content: Text('Invalid token, please sign in again'))); messenger.showSnackBar(const SnackBar(content: Text('Invalid token, please sign in again')));
prefs.remove('token');
debugPrint(e.toString()); debugPrint(e.toString());
logout();
return false; return false;
} }
return true; return true;
} }
void logout() async {
final prefs = await SharedPreferences.getInstance();
prefs.remove('token');
prefs.remove('refresh-token');
prefs.remove('id');
}

View File

@ -25,10 +25,7 @@ class _SideMenuState extends State<SideMenu> {
} }
void _logout() async { void _logout() async {
final prefs = await SharedPreferences.getInstance(); api.logout();
prefs.remove('token');
prefs.remove('id');
setState(() { setState(() {
user = null; user = null;

View File

@ -19,15 +19,15 @@ class _LoginPageState extends State<LoginPage> {
final passwordInput = TextEditingController(); final passwordInput = TextEditingController();
Future<void> _login() async { Future<void> _login() async {
final token = await api.request(context, api.ApiService.auth, 'POST', '/api/Users/login', { final response = await api.request(context, api.ApiService.auth, 'POST', '/api/Users/login', {
'email': emailInput.text, 'email': emailInput.text,
'password': passwordInput.text, 'password': passwordInput.text,
}); });
if (token == null) return; if (response == null) return;
// Assuming token is a JSON string // Assuming token is a JSON string
Map<String, dynamic> json = jsonDecode(token); Map<String, dynamic> json = jsonDecode(response);
Login jsonUser = Login.fromJson(json); Login jsonUser = Login.fromJson(json);
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();

View File

@ -17,11 +17,11 @@ import 'package:http/http.dart' as http;
import 'dart:developer'; import 'dart:developer';
void main() async { void main() async {
// Refresh JWT on startup
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
debugPrint('token: ' + (prefs.getString('token') ?? '') + ' reffresshh: ' + (prefs.getString("refresh-token") ?? ''));
if (prefs.getString("token") != null && prefs.getString("refresh-token") != null) { if (prefs.getString("token") != null && prefs.getString("refresh-token") != null) {
final token = await api.request(null, api.ApiService.auth, "POST", "/RefreshToken", {'refresh-token': prefs.getString("refresh-token")}); final token = await api.request(null, api.ApiService.auth, "POST", "/RefreshToken", {'refreshToken': prefs.getString("refresh-token")});
debugPrint(token); if (token != null) prefs.setString("token", token);
} }
runApp(const MyApp()); runApp(const MyApp());