Example #1
0
        public async Task <JsonResult> Token([FromBody] TokenModel model)
        {
            if (!string.IsNullOrEmpty(model.AccessToken))
            {
                var handler = new JwtSecurityTokenHandler();
                var token   = handler.ReadJwtToken(model.AccessToken);
                var now     = DateTime.UtcNow;

                if (now >= token.ValidTo)
                {
                    var userId    = token.Claims.FirstOrDefault().Value;
                    var intUserId = int.Parse(userId);

                    var dbUser = await _dbContext.Users.FirstOrDefaultAsync(x => x.Id == intUserId)
                                 .ConfigureAwait(false);

                    var dbToken = await _dbContext.Tokens.FirstOrDefaultAsync(x => x.Id == dbUser.TokenId)
                                  .ConfigureAwait(false);

                    if (dbToken.RefreshToken == model.RefreshToken)
                    {
                        await TokenHelpers.GenerateToken(userId, dbToken, _dbContext);

                        return(new JsonResult(new TokenResponse
                        {
                            access_token = dbToken.AccessToken,
                            refresh_token = dbToken.RefreshToken,
                            expired_in = (dbToken.TokenExpiredDate - now).TotalSeconds
                        }));
                    }
                    else
                    {
                        throw new Exception("Неверный Refresh Token");
                    }
                }
                else
                {
                    throw new Exception("Срок действия вашего токена ещё не истёк");
                }
            }

            throw new Exception("Срок действия вашего токена ещё не истёк");
        }
Example #2
0
        public async Task <IActionResult> SignIn([FromBody] SignInModel model)
        {
            // Валидация
            if (string.IsNullOrEmpty(model.login.Trim()) || string.IsNullOrEmpty(model.pass.Trim()))
            {
                throw new Exception(TextResource.Auth_EmptyValues);
            }

            if (model.login.Length < 5 || model.login.Length > 20)
            {
                throw new Exception(TextResource.Auth_LoginWrongLength);
            }

            if (model.pass.Length < 4 || model.pass.Length > 30)
            {
                throw new Exception(TextResource.Auth_PassWrongLength);
            }

            var dbUser = await _dbContext.Users.FirstOrDefaultAsync(x => x.Login == model.login)
                         .ConfigureAwait(false);

            if (dbUser == null)
            {
                throw new Exception("Неправильный логин или пароль");
            }

            var password = PasswordHelpers.EncryptPassword(model.pass, dbUser.Pass.Salt);

            if (!PasswordHelpers.SlowEquals(password, dbUser.Pass.Password))
            {
                throw new Exception("Неправильный логин или пароль");
            }

            var now = DateTime.UtcNow;

            var user = new
            {
                dbUser.Id,
                dbUser.Login,
                dbUser.FirstName,
                dbUser.MiddleName,
                dbUser.Surname,
                dbUser.Email,
                dbUser.BirthDate,
                dbUser.City
            };

            var dbToken = await _dbContext.Tokens.FirstOrDefaultAsync(x => x.Id == dbUser.TokenId)
                          .ConfigureAwait(false);

            if (dbToken != null && dbToken.TokenExpiredDate >= now)
            {
                return(new JsonResult(new SignInResponse
                {
                    access_token = dbToken.AccessToken,
                    refresh_token = dbToken.RefreshToken,
                    expired_in = (dbToken.TokenExpiredDate - now).TotalSeconds,
                    user = user
                }));
            }

            bool isFirst = false;

            // Если пользователь авторизуется впервые
            if (dbToken == null)
            {
                dbToken = new Token();
                isFirst = true;
            }

            await TokenHelpers.GenerateToken(dbUser.Id.ToString(), dbToken, _dbContext, isFirst)
            .ConfigureAwait(false);

            dbUser.TokenId = dbToken.Id;

            await _dbContext.SaveChangesAsync(true)
            .ConfigureAwait(false);

            return(new JsonResult(new SignInResponse
            {
                access_token = dbToken.AccessToken,
                refresh_token = dbToken.RefreshToken,
                expired_in = (dbToken.TokenExpiredDate - now).TotalSeconds,
                user = user
            }));
        }
Example #3
0
        public async Task <IActionResult> Login([FromBody] LoginUserDto model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new ResponseModel()
                {
                    Message = "Model State is not valid",
                    Result = false,
                    Status = 400
                }));
            }


            if (!IsValidEmail(model.Email))
            {
                return(BadRequest(new ResponseModel()
                {
                    Message = "Please provide a valid email",
                    Result = false,
                    Status = 404
                }));
            }

            var user = _userService.GetByEmail(model.Email);

            if (user == null)
            {
                return(BadRequest(new ResponseModel()
                {
                    Message = "User Not Found",
                    Status = 404,
                    Result = false
                }));
            }
            TokenHelpers tokenHelpers = new TokenHelpers(_configuration);

            if (!user.IsActive)
            {
                string VerificationToken = tokenHelpers.GenerateVerificationToken(model.Email);

                string url = _configuration.Value.FrontUrl + "/token=" + VerificationToken;

                string body = $"Please click <a href = {url} >link</a> link to verify YourAccount";


                await _emailService.SendMail("Verify Account", body, model.Email);

                return(BadRequest(new ResponseModel()
                {
                    Message = "Account is not active please active your account. New Activation link has been sent",
                    Status = 404,
                    Result = false
                }));
            }

            if (!HashingHelper.VerifyPasswordHash(model.Password, user.PasswordHash, user.PasswordSalt))
            {
                return(BadRequest(new ResponseModel()
                {
                    Message = "Password is wrong. Try Again.",
                    Result = false,
                    Status = 404
                }));
            }


            TokenResultModel token = tokenHelpers.GenerateToken(user);

            user.LastLoggedInDate = DateTime.Now;

            await _userService.UpdateAsync(user);

            return(Ok(new
            {
                user = new
                {
                    user.Id,
                    user.Name,
                    user.Surname,
                    user.Email,
                    user.Address,
                    role = user.Role.ToString(),
                    user.Phone,
                    user.ImageUrl,
                    user.LastLoggedInDate
                },
                token
            }));
        }