public async Task <IActionResult> Authenticate([FromBody] LoginRequest request) { try { if (request != null) { var user = await UserHandler.Authenticate(request); if (user == null) { Logger.LogInformation("User authentication failed: " + request.Email); return(Unauthorized()); } if (!user.IsSystemAccount) { Logger.LogInformation("User is not a system account: " + request.Email); return(Unauthorized()); } Logger.LogInformation("User authenticated"); var jwt = JwtSecurity.GenerateToken(user.UserId, user.Email); var loginResponse = new { User = user, CSToken = jwt }; var response = JsonConvert.SerializeObject(loginResponse, new JsonSerializerSettings { Formatting = Formatting.None }); return(Ok(loginResponse)); } return(StatusCode(408, new ErrorResponse() { Message = "Bad Login Request" })); } catch (Exception ex) { Logger.LogError(ex.ToString()); return(StatusCode(505, ex.Message)); } }
public async Task <IActionResult> RefreshToken([FromRoute] Guid userId, [FromHeader] string authorization, [FromBody] Device deviceInfo) { try { //Null checks if (authorization == null) { return(StatusCode(500, new ErrorResponse() { Message = "Authorization token is missing from header" })); } if (deviceInfo.RefreshToken == null) { return(StatusCode(500, new ErrorResponse() { Message = "Refresh Token is missing from Json body" })); } //Token verification var updatedAuthorization = authorization.Replace("Bearer ", ""); var verifyToken = UserHandler.ReadToken(updatedAuthorization, userId); if (!verifyToken) { return(StatusCode(500, new ErrorResponse() { Message = "UserId does not match Authorized User associated with provided Auth Token" })); } var userInfo = await UserHandler.GetUserById(userId); if (userInfo != null) { var authUser = userInfo; var verifyRefreshToken = UserHandler.ReadToken(deviceInfo.RefreshToken, userId); if (verifyRefreshToken) { var jwt = JwtSecurity.GenerateToken(authUser.UserId, authUser.Email); var jwtRefresh = JwtSecurity.GenerateRefreshToken(authUser.UserId, authUser.Email); var loginResponse = new { User = authUser, CSToken = jwt, RefreshToken = jwtRefresh }; var response = JsonConvert.SerializeObject(loginResponse, new JsonSerializerSettings { Formatting = Formatting.None }); return(Ok(loginResponse)); } return(StatusCode(500, new ErrorResponse() { Message = "Device Refresh token is invalid" })); } Logger.LogInformation("Unable to retrieve user information with the UserId provided"); return(StatusCode(401, new ErrorResponse() { Message = "Unable to retrieve user information with the UserId provided" })); } catch (Exception ex) { Logger.LogError(ex.ToString()); return(StatusCode(505, ex.Message)); } }