Example #1
0
        public async Task <Response <AuthResultDto> > Handle(LoginStudentCommand request, CancellationToken cancellationToken)
        {
            var user = await _userManager.FindByEmailAsync(request.Email);

            if (user is null)
            {
                return(Response.Fail <AuthResultDto>("User doesn't exist!"));
            }

            var passwordIsValid = await _userManager.CheckPasswordAsync(user, request.Password);

            if (!passwordIsValid)
            {
                return(Response.Fail <AuthResultDto>("Password is wrong!"));
            }

            var userRoles = await _userManager.GetRolesAsync(user);

            var role = userRoles.Contains("Admin") ? "Admin" : "Student";

            var result = new AuthResultDto
            {
                Token = JwtTokenGenerator.GenerateToken(user.Email, user.Id,
                                                        _jwtSettings.Secret, role)
            };

            return(Response.Success <AuthResultDto>(result, "Token is created successfully"));
        }
Example #2
0
        public IActionResult SignIn(UserDTO userDTO)
        {
            try
            {
                ValidationResult result = _identityService.ValidationPassword(userDTO.Email, userDTO.Password);

                if (!result.Succeeded)
                {
                    return(StatusCode(422, "Email or Password is not correct."));
                }

                // generate a token and return
                var user  = result.User;
                var token = JwtTokenGenerator.GenerateToken(result.User, _appSettings.Issuer, _appSettings.Secret);

                return(Ok(new UserDTO()
                {
                    Id = user.Id,
                    UserName = user.UserName,
                    Email = user.Email,
                    Token = token
                }));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Example #3
0
        public async Task <SignInResultViewModel> SignInStepTwo(SignInStepTwoViewModel model)
        {
            var phone = model.PhoneNumber.Trim().ToNormalPhoneNumber();
            var code  = model.SecurityCode.Trim().ToNormalNumber();

            var user = await _context.Users.FirstOrDefaultAsync(w => w.PhoneNumber == phone);

            if (user == null)
            {
                throw new Exception("کاربر مورد نظر یافت نشد");
            }

            if ((user.SecurityCode != code) ||
                (user.SecurityCode == code && user.SecurityCodeExpiration < DateTime.Now))
            {
                throw new Exception("کد وارد شده معتبر نیست");
            }

            return(new SignInResultViewModel
            {
                PhoneNumber = phone,
                FullName = user.FullName,
                RoleEnum = user.RoleEnum,
                RoleTitle = ((RoleEnum)user.RoleEnum).GetEnumName(),
                Token = _jwtTokenGenerator.GenerateToken(user.Id, true)
            });
        }
Example #4
0
        public IActionResult SignUp(UserDTO userDTO)
        {
            try
            {
                var user = _mapper.Map <User>(userDTO);
                user = _identityService.SignUp(user, userDTO.Password);

                var token = JwtTokenGenerator.GenerateToken(user, _appSettings.Issuer, _appSettings.Secret);

                return(Ok(new UserDTO()
                {
                    Id = user.Id,
                    UserName = user.UserName,
                    Email = user.Email,
                    Token = token
                }));
            }
            catch (DomainException dx)
            {
                return(Conflict($"This email has already been registered. Detail: {dx.Message}"));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
 public HttpResponseMessage Post([FromBody] User user)
 {
     try
     {
         var userExists = _entities.Users.Any(e => e.Email == user.Email);
         if (userExists)
         {
             return(Request.CreateResponse(HttpStatusCode.Conflict, "User already exists"));
         }
         if (!BusinessLoginHelper.IsValidEmail(user.Email))
         {
             return(Request.CreateResponse(HttpStatusCode.Conflict, "Email address not valid"));
         }
         user.CreatedDateTime  = DateTime.Now;
         user.ModifiedDateTime = DateTime.Now;
         user.Password         = new HashPassword().encrypt(user.Password);
         var jwtToken = _tokenGenerator.GenerateToken(user.Email, user.Password);
         user.Token = jwtToken;
         _entities.Users.Add(user);
         _entities.SaveChanges();
         var message = Request.CreateResponse(HttpStatusCode.Created, "User successfully created");
         message.Headers.Location = new Uri(Request.RequestUri + user.UserId.ToString());
         return(message);
     }
     catch (Exception ex)
     {
         return(Request.CreateResponse(HttpStatusCode.BadRequest, ex));
     }
 }
Example #6
0
        public async Task <ActionResult <ApiResultViewModel <SessionViewModel> > > Login([FromBody] LoginInputModel inputModel,
                                                                                         CancellationToken cancellationToken)
        {
            var account = await _accountManager.FindByEmailAsync(inputModel.Email, cancellationToken);

            if (account == null || account.IsArchived)
            {
                return(BadRequest("invalid_email", "Account not found"));
            }

            if (!PasswordHash.ValidatePassword(inputModel.Password, account.PasswordHash))
            {
                return(BadRequest("invalid_username_or_password", "Invalid Email or Password!"));
            }

            var token = _tokenGenerator.GenerateToken(TimeSpan.FromDays(365),
                                                      new Claim(JwtRegisteredClaimNames.Jti, account.Id.ToString()),
                                                      new Claim(JwtRegisteredClaimNames.Sub, account.Email),
                                                      new Claim("Timezone", account.Timezone));

            var session = new Session
            {
                AccessToken      = token,
                AccountId        = account.Id,
                CreationDateTime = DateTime.UtcNow,
                StateId          = SessionStateIds.Created,
                SourceAppId      = AppIds.Game
            };

            await _sessionManager.SaveAsync(session, cancellationToken);

            return(CreatedData(SessionViewModel.Map(session)));
        }
Example #7
0
        public async Task <ActionResult <ApiResultViewModel <AccountViewModel> > > Register(
            [FromBody] RegisterInputModel inputModel, CancellationToken cancellationToken)
        {
            var account = await _accountManager.FindByEmailAsync(inputModel.Email, cancellationToken);

            if (account != null)
            {
                return(BadRequest("invalid_email", "Email already exists"));
            }

            account = new Account
            {
                Email                = inputModel.Email,
                PasswordHash         = PasswordHash.CreateHash(inputModel.Password),
                StatusId             = AccountStatusIds.Active,
                Timezone             = "Asia/Tehran",
                ReceiveNotifications = true,
                SearchableByEmailAddressOrUsername = true,
                FriendsOnlyBattleInvitations       = false
            };
            account.Nickname         = account.Email.Substring(0, account.Email.IndexOf('@'));
            account.RegisterDateTime = DateTime.UtcNow;
            account.GenderId         = GenderIds.Male;
            account = await _accountManager.SaveAsync(account, cancellationToken);

            var accountStats = new AccountStatsSummary
            {
                AccountId = account.Id,
                Level     = 1
            };
            await _statsManager.SaveAsync(accountStats, cancellationToken);

            await SetDefaultAvatar(account, cancellationToken);

            await _dataContext.SaveChangesAsync(cancellationToken);

            var token = _tokenGenerator.GenerateToken(TimeSpan.FromDays(365),
                                                      new Claim(JwtRegisteredClaimNames.Jti, account.Id.ToString()),
                                                      new Claim(JwtRegisteredClaimNames.Sub, account.Email),
                                                      new Claim("Timezone", account.Timezone));

            var session = new Session
            {
                AccessToken      = token,
                AccountId        = account.Id,
                CreationDateTime = DateTime.UtcNow,
                StateId          = SessionStateIds.Created,
                SourceAppId      = AppIds.Game
            };

            await _sessionManager.SaveAsync(session, cancellationToken);

            return(CreatedData(RegisterViewModel.GetRegisterViewModel(AccountViewModel.Map(account),
                                                                      SessionViewModel.Map(session))));
        }
Example #8
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole();
            app.UseJwtBearerAuthentication(new JwtBearerOptions
            {
                AutomaticAuthenticate     = true,
                AutomaticChallenge        = true,
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = AuthOptions.ISSUER,
                    ValidateAudience         = true,
                    ValidAudience            = AuthOptions.AUDIENCE,
                    ValidateLifetime         = true,
                    IssuerSigningKey         = AuthOptions.GetSymmetricSecurityKey(),
                    ValidateIssuerSigningKey = true,
                }
            });
            RouteBuilder routeBuilder = new RouteBuilder(app);

            routeBuilder.MapGet("api/code/{id:int}", context =>
            {
                if (context.Authentication.HttpContext.User.Identity.IsAuthenticated)
                {
                    var res = AppConfiguration[context.GetRouteValue("id").ToString()];
                    return(context.Response.WriteAsync(res == null ? (context.Response.StatusCode = 400).ToString()
                    : $"{AppConfiguration["Codeprefix"]}{DateTime.Now.Month}{DateTime.Now.Year}-{res}"));
                }
                return(context.Response.WriteAsync((context.Response.StatusCode = 401).ToString()));
            });
            routeBuilder.MapPost("token/", context =>
            {
                var token  = new  JwtTokenGenerator();
                var identy = token.GetIdentity(context.Request.Headers["username"], context.Request.Headers["password"]);
                if (identy == null)
                {
                    return(context.Response.WriteAsync("Invalid username or password."));;
                }
                var response = new
                {
                    access_token = token.GenerateToken(identy),
                    username     = identy.Name
                };
                context.Response.ContentType = "application/json";
                return(context.Response.WriteAsync(JsonConvert.SerializeObject(response, new JsonSerializerSettings {
                    Formatting = Formatting.Indented
                })));
            });

            app.UseRouter(routeBuilder.Build());
        }
        public async Task <Response <AuthResultDto> > Handle(RegisterStudentCommand request, CancellationToken cancellationToken)
        {
            var existingStudent = await _userManager.FindByEmailAsync(request.Email);

            if (existingStudent != null)
            {
                return(Response.Fail <AuthResultDto>($"User with this email ({request.Email} already exists)"));
            }

            var schoolClass = await _context.SchoolClasses.AsNoTracking()
                              .SingleOrDefaultAsync(c => c.Id == request.SchoolClassId, cancellationToken);

            if (schoolClass is null)
            {
                return(Response.Fail <AuthResultDto>(
                           $"In our school we don't have class with Id#{request.SchoolClassId}"));
            }

            try
            {
                var newUser = _mapper.Map <Student>(request);
                newUser.AbsentMarkCount = 0;
                newUser.NormalizedEmail = request.Email.ToUpper();
                var ph = new PasswordHasher <Student>();
                newUser.PasswordHash  = ph.HashPassword(newUser, request.Password);
                newUser.SchoolClassId = request.SchoolClassId;
                await _context.Students.AddAsync(newUser, cancellationToken);

                var isAdded = await _context.SaveChangesAsync(cancellationToken);

                if (isAdded == 0)
                {
                    return(Response.Fail <AuthResultDto>("Problem occured while creating user entity"));
                }

                await _userManager.AddToRoleAsync(newUser, "Student");

                var result = new AuthResultDto
                {
                    Token = JwtTokenGenerator.GenerateToken(newUser.Email, newUser.Id,
                                                            _jwtSettings.Secret, "Student")
                };
                return(Response.Success <AuthResultDto>(result, "Token is created successfully"));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Example #10
0
        public async Task <IActionResult> Login(UserForLoginDTO userForLoginDto)
        {
            User userFromRepo = await repository.LoginAsync(userForLoginDto.UsernameOrEmail.ToLower(), userForLoginDto.Password);

            if (userFromRepo == null)
            {
                return(Unauthorized("Provided login or password is incorrect"));
            }

            JwtTokenGenerator tokenGenerator  = new JwtTokenGenerator();
            string            key             = config.GetSection("AppSettings:TokenKey").Value;
            DateTime          tokenExpiration = DateTime.Now.AddHours(12);


            return(Ok(new{ token = tokenGenerator.GenerateToken(userFromRepo.Id, userFromRepo.Username, key, tokenExpiration) }));
        }
Example #11
0
        public async Task <ActionResult <ApiResultViewModel <SessionViewModel> > > Login([FromBody] LoginInputModel model,
                                                                                         CancellationToken cancellationToken)
        {
            var account = await _accountManager.FindByEmailAsync(model.Email, cancellationToken);

            if (account == null)
            {
                return(BadRequest("invalid_username_or_password", "Invalid Username or Password!"));
            }

            if (!PasswordHash.ValidatePassword(model.Password, account.PasswordHash))
            {
                return(BadRequest("invalid_username_or_password", "Invalid Username or Password!"));
            }

            var roles = await _accountManager.GetRolesAsync(account, cancellationToken);

            if (!roles.Contains(RoleIds.Admin))
            {
                return(Forbidden());
            }

            if (!account.IsEmailVerified)
            {
                return(BadRequest("email_not_verified", "Please verify your email to log in."));
            }

            var token = _tokenGenerator.GenerateToken(TimeSpan.FromDays(365),
                                                      new Claim(JwtRegisteredClaimNames.Jti, account.Id.ToString()),
                                                      new Claim(JwtRegisteredClaimNames.Sub, account.Email));

            var session = new Session
            {
                AccessToken      = token,
                AccountId        = account.Id,
                CreationDateTime = DateTime.UtcNow,
                StateId          = SessionStateIds.Created,
                SourceAppId      = AppIds.Admin
            };

            await _sessionManager.SaveAsync(session, cancellationToken);

            return(CreatedData(SessionViewModel.Map(session)));
        }
Example #12
0
        public async Task <IActionResult> Login([FromForm] LoginViewModel loginDetails)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var user = await userManager.FindByNameAsync(encoder.Encode(loginDetails.Username));

            if (user != null)
            {
                await signInManager.SignOutAsync();

                var result = await signInManager.PasswordSignInAsync(user, loginDetails.Password, false, false);

                if (result.Succeeded)
                {
                    var token = tokenGenerator.GenerateToken(user);
                    if (result.Succeeded)
                    {
                        var u = await context.Users.FirstOrDefaultAsync(u => u.UserName == encoder.Encode(loginDetails.Username));

                        if (u == null)
                        {
                            return(BadRequest("User does not exist"));
                        }

                        var roles = await userManager.GetRolesAsync(u);

                        return(new OkObjectResult(new LoginResultViewModel
                        {
                            User = new UserViewModel(u, encoder, roles),
                            Token = token,
                        }));
                    }
                    else
                    {
                        return(Forbid());
                    }
                }
            }
            return(Forbid());
        }
Example #13
0
        /// <summary>
        /// This method is to validate token
        /// </summary>
        /// <returns>true or false</returns>
        private async Task <bool> ValidateJWTToken()
        {
            try
            {
                var config = Context.RequestServices.GetService <IConfiguration>();

                if (!string.IsNullOrEmpty(Context.Request.Headers["Authorization"].ToString()))
                {
                    var      requestAuthHeader = Context.Request.Headers["Authorization"].ToString();
                    string[] authToken         = requestAuthHeader.Split(" ");
                    var      token             = authToken[1];
                    var      handler           = new JwtSecurityTokenHandler();
                    var      tokenString       = handler.ReadJwtToken(token) as JwtSecurityToken;
                    long     expireTime        = long.Parse(tokenString.Claims.FirstOrDefault(claim => claim.Type == "exp").Value);

                    long currentTime = (long)DateTime.Now.ToUniversalTime().Subtract(
                        new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
                        ).TotalSeconds;


                    _user.FirstName = tokenString.Claims.FirstOrDefault(claim => claim.Type == "given_name").Value;
                    _user.LastName  = tokenString.Claims.FirstOrDefault(claim => claim.Type == "family_name").Value;
                    _user.UserId    = int.Parse(tokenString.Claims.FirstOrDefault(claim => claim.Type == "UserId").Value);
                    _user.TenantId  = int.Parse(tokenString.Claims.FirstOrDefault(claim => claim.Type == "TenantId").Value);
                    _user.UserEmail = tokenString.Claims.FirstOrDefault(claim => claim.Type == "email").Value;

                    if ((expireTime - currentTime) <= 500)
                    {
                        if (string.IsNullOrEmpty(Context.Response.Headers["Authorization"]))
                        {
                            JwtTokenGenerator jwt      = new JwtTokenGenerator(config);
                            AuthRequest       newToken = jwt.GenerateToken(_user);
                            Context.Response.Headers.Add("Access-Control-Allow-Headers", "Authorization");
                            Context.Response.Headers.Add("Authorization", newToken.Token);
                        }
                    }
                }
            }
            catch { return(false); }
            return(true);
        }
Example #14
0
        public void GenerateToken_ShouldReturnTokenString()
        {
            const string username = "******";

            var identityUser = new IdentityUser {
                Id = "testId"
            };

            var expires = DateTime.Now.AddDays(1);

            var tokenHandler = new JwtSecurityTokenHandler();

            var tokenString  = _tokenGenerator.GenerateToken(username, identityUser);
            var decodedToken = tokenHandler.ReadJwtToken(tokenString);

            Assert.Contains(decodedToken.Claims.Where(x => x.Type == "id"),
                            x => x.Value == "testId");
            Assert.Contains(decodedToken.Claims.Where(x => x.Type == JwtRegisteredClaimNames.Sub),
                            x => x.Value == "testUsername");
            Assert.True(decodedToken.Issuer == "testIssuer");
        }
        public async Task <Response <AuthResultDto> > Handle(RegisterPsychologistCommand request, CancellationToken cancellationToken)
        {
            var existingPsychologist = await _userManager.FindByEmailAsync(request.Email);

            if (existingPsychologist != null)
            {
                return(Response.Fail <AuthResultDto>($"User with this email ({request.Email} already exists)"));
            }

            try
            {
                var newUser = _mapper.Map <Psychologist>(request);
                newUser.NormalizedEmail = request.Email.ToUpper();
                var ph = new PasswordHasher <Psychologist>();
                newUser.PasswordHash = ph.HashPassword(newUser, request.Password);
                await _context.Psychologists.AddAsync(newUser, cancellationToken);

                var isAdded = await _context.SaveChangesAsync(cancellationToken);

                if (isAdded == 0)
                {
                    return(Response.Fail <AuthResultDto>("Problem occured while creating user entity"));
                }

                await _userManager.AddToRoleAsync(newUser, "Psychologist");

                var result = new AuthResultDto
                {
                    Token = JwtTokenGenerator.GenerateToken(newUser.Email, newUser.Id,
                                                            _jwtSettings.Secret, "Psychologist")
                };
                return(Response.Success <AuthResultDto>(result, "Token is created successfully"));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Example #16
0
        public async Task <IActionResult> ExecuteAsync(LoginViewModel loginDetails, ModelStateDictionary modelState)
        {
            if (!modelState.IsValid)
            {
                return(new BadRequestResult());
            }

            var user = await userManager.FindByNameAsync(loginDetails.Username);

            if (user != null)
            {
                await signInManager.SignOutAsync();

                var result = await signInManager.PasswordSignInAsync(user, loginDetails.Password, false, false);

                if (result.Succeeded)
                {
                    var token = tokenGenerator.GenerateToken(user);
                    return(new OkObjectResult(token));
                }
            }
            return(new BadRequestResult());
        }