Esempio n. 1
0
        public async Task <IActionResult> Login([FromBody] LoginViewModel model, string returnUrl = null)
        {
            // First get the return url - the url which the user was trying to access initially
            ViewData["ReturnUrl"] = returnUrl;

            if (ModelState.IsValid)
            {
                try
                {
                    var jwtToken = await _authSvc.Auth(model);

                    const int expireTime = 60; // set the value to 60 - as dont want the admin cookie to stay in browser for longer

                    _cookieSvc.SetCookie("access_token", jwtToken.Token, expireTime);
                    _cookieSvc.SetCookie("user_id", jwtToken.UserId, expireTime);
                    _cookieSvc.SetCookie("username", jwtToken.Username, expireTime);
                    Log.Information($"User {model.Email} logged in.");

                    return(Ok("Success"));
                }
                catch (Exception ex)
                {
                    Log.Error("An error occurred while seeding the database  {Error} {StackTrace} {InnerException} {Source}",
                              ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
                }
            }

            ModelState.AddModelError("", "Invalid Username/Password was entered");

            Log.Error("Invalid Username/Password was entered");

            return(Unauthorized("Please Check the Login Credentials - Invalid Username/Password was entered"));
        }
Esempio n. 2
0
      public async Task <IActionResult> Login([FromBody] LoginViewModel model, string returnUrl = null)
      {
          ViewData["ReturnUrl"] = returnUrl;
          if (ModelState.IsValid)
          {
              try
              {
                  var jwtTokenResponse = await _authenticateSvc.Auth(model);

                  const int expireTime = 60;
                  _cookieSvc.SetCookie(AccessToken, jwtTokenResponse.Token, expireTime);
                  _cookieSvc.SetCookie(User_Id, jwtTokenResponse.UserId, expireTime);
                  _cookieSvc.SetCookie("username", jwtTokenResponse.Username, expireTime);
                  Log.Information($"User {model.Email} :Login success");
                  return(Ok("success"));
              }
              catch (Exception ex)
              {
                  Log.Error("Error while Login Post with user {Error} {StackTrace} {InnerException} {Source}",
                            ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
              }
          }
          ModelState.AddModelError("", "Invaid UserName/Password was entered");
          Log.Error("Invaid UserName / Password was entered");
          return(Unauthorized("Please Check UserNAME/Password"));
      }
Esempio n. 3
0
        public async Task <TokenResponseModel> GenerateNewToken()
        {
            try
            {
                var loggedInUserId = GetLoggedInUserId();
                var user           = await _userManager.FindByIdAsync(loggedInUserId);

                // password was already validated - therefore we need to check if the two-factor token exists
                if (user == null)
                {
                    return(CreateErrorResponseToken("Something went wrong. Please try again later", HttpStatusCode.Unauthorized));
                }

                var accessToken = await CreateAccessToken(user);

                var refreshTokenExpireTime = accessToken.RefreshTokenExpiration.Subtract(DateTime.UtcNow).TotalMinutes;
                // set cookie for jwt and refresh token
                // Expiry time for cookie - When Refresh token expires all other cookies should expire
                // therefor set all the cookie expiry time to refresh token expiry time
                _cookieSvc.SetCookie("access_token", accessToken.Token.ToString(), Convert.ToInt32(refreshTokenExpireTime));
                _cookieSvc.SetCookie("refreshToken", accessToken.RefreshToken, Convert.ToInt32(refreshTokenExpireTime));
                _cookieSvc.SetCookie("loginStatus", "1", Convert.ToInt32(refreshTokenExpireTime), false, false);
                _cookieSvc.SetCookie("username", user.UserName, Convert.ToInt32(refreshTokenExpireTime), false, false);
                _cookieSvc.SetCookie("userRole", user.UserRole, Convert.ToInt32(refreshTokenExpireTime), false, false);
                _cookieSvc.SetCookie("user_id", accessToken.UserId, Convert.ToInt32(refreshTokenExpireTime));

                return(accessToken);
            }
            catch (Exception ex)
            {
                Log.Error("An error occurred at GenerateNewToken(TwoFactorResponseModel model)  {Error} {StackTrace} {InnerException} {Source}",
                          ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
            }

            return(CreateErrorResponseToken("Request Not Supported", HttpStatusCode.Unauthorized));
        }
Esempio n. 4
0
        private async Task <TokenResponseModel> GenerateNewToken(TokenRequestModel model)
        {
            try
            {
                // check if there's an user with the given username
                var user = await _userManager.FindByEmailAsync(model.Email);

                // Validate credentials
                if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
                {
                    // Create & Return the access token which contains JWT and Refresh Token
                    var accessToken = await CreateAccessToken(user);

                    var expireTime             = accessToken.Expiration.Subtract(DateTime.UtcNow).TotalMinutes;
                    var refreshTokenExpireTime = accessToken.RefreshTokenExpiration.Subtract(DateTime.UtcNow).TotalMinutes;

                    // set cookie for jwt and refresh token
                    _cookieSvc.SetCookie("access_token", accessToken.Token.ToString(), Convert.ToInt32(refreshTokenExpireTime));
                    _cookieSvc.SetCookie("refreshToken", accessToken.RefreshToken, Convert.ToInt32(refreshTokenExpireTime));
                    _cookieSvc.SetCookie("loginStatus", "1", Convert.ToInt32(refreshTokenExpireTime), false, false);
                    _cookieSvc.SetCookie("username", user.UserName, Convert.ToInt32(refreshTokenExpireTime), false, false);
                    _cookieSvc.SetCookie("userRole", user.UserRole, Convert.ToInt32(refreshTokenExpireTime), false, false);
                    _cookieSvc.SetCookie("user_id", accessToken.UserId, Convert.ToInt32(refreshTokenExpireTime));
                    return(accessToken);
                }
                return(CreateErrorResponseToken("Invalid Username/Password", HttpStatusCode.Unauthorized));
            }
            catch (Exception ex)
            {
                Log.Error("An error occurred while seeding the database  {Error} {StackTrace} {InnerException} {Source}",
                          ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
                return(CreateErrorResponseToken("There was an Error While Processing this request", HttpStatusCode.InternalServerError));
            }
        }
Esempio n. 5
0
        public async Task <TwoFactorResponseModel> SendTwoFactorAsync(TwoFactorRequestModel model)
        {
            var twoFactorResponse = new TwoFactorResponseModel();
            var result            = new TwoFactorCodeModel();

            try
            {
                var protectorProvider = _provider.GetService <IDataProtectionProvider>();

                var userIdFromHeader = _httpContextAccessor.HttpContext.Request.Headers["user_id"];
                var twoFactorToken   = model.TwoFactorToken;

                // If two factor token is null we dont want to further execute this method
                if (!string.IsNullOrEmpty(twoFactorToken) && !string.IsNullOrEmpty(userIdFromHeader))
                {
                    var userId = DecryptData(userIdFromHeader, _dataProtectionKeys.ApplicationUserKey).ToString();
                    // First find user with that Id id two-factor Table
                    // If user was found, check if the token is valid or expired
                    var userResult = await _db.TwoFactorCodes.Where(x =>
                                                                    x.UserId == userId &&
                                                                    x.CodeExpired == false &&
                                                                    x.CodeIsUsed == false &&
                                                                    x.ExpiryDate > DateTime.UtcNow).FirstOrDefaultAsync();

                    if (userResult != null)
                    {
                        // Decrypted Two-Factor-Token from request
                        var protector = protectorProvider.CreateProtector(userResult.EncryptionKey2Fa);
                        var decryptedTwoFactorToken = protector.Unprotect(twoFactorToken);

                        // Get the Application User
                        var appUser = await _userManager.FindByIdAsync(userId);

                        // If both the values match request vs DB
                        if (userResult.Token != null && decryptedTwoFactorToken != null && userResult.Token == decryptedTwoFactorToken)
                        {
                            // check in current request if they want to remember
                            userResult.RememberDevice            = model.RememberDevice;
                            await using var dbContextTransaction = await _db.Database.BeginTransactionAsync();

                            _db.Entry(userResult).State = EntityState.Modified;
                            await _db.SaveChangesAsync();

                            await dbContextTransaction.CommitAsync();

                            twoFactorResponse.IsValid         = true;
                            twoFactorResponse.Email           = appUser.Email;
                            twoFactorResponse.Code            = userResult.TwoFactorCode;
                            twoFactorResponse.RememberDevice  = userResult.RememberDevice;
                            twoFactorResponse.ResponseMessage = new ResponseStatusInfoModel
                            {
                                Message    = "Authentication Success",
                                StatusCode = HttpStatusCode.OK
                            };
                            protector = protectorProvider.CreateProtector(_dataProtectionKeys.ApplicationUserKey);
                            var protectedUserId = protector.Protect(userId);
                            _cookieSvc.SetCookie("user_id", protectedUserId, Convert.ToInt32(userResult.ExpiryDate.Subtract(DateTime.UtcNow).TotalMinutes));
                            return(twoFactorResponse);
                        }
                    }
                }
                twoFactorResponse.IsValid         = false;
                twoFactorResponse.Email           = string.Empty;
                twoFactorResponse.Code            = string.Empty;
                twoFactorResponse.RememberDevice  = false;
                twoFactorResponse.ResponseMessage = new ResponseStatusInfoModel
                {
                    Message    = "Authentication Failed",
                    StatusCode = HttpStatusCode.Unauthorized
                };
            }
            catch (Exception ex)
            {
                Log.Error("An error occurred at ValidateTwoFactorAsync {Error} {StackTrace} {InnerException} {Source}",
                          ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
            }

            return(twoFactorResponse);
        }