示例#1
0
        public async Task <IHttpActionResult> Login([FromBody] LoginViewModel model)
        {
            if (model == null)
            {
                model = new LoginViewModel();
                Validate(model);
            }

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            // Verify the capcha first.
            var bIsCaptchaValid =
                await _captchaService.IsCaptchaValidAsync(model.ClientCaptchaCode, null, CancellationToken.None);

            if (!bIsCaptchaValid)
            {
                return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Forbidden,
                                                                   HttpMessages.CaptchaInvalid)));
            }

            // Get profile from system.
            var profile = await _userService.LoginAsync(model, CancellationToken.None);

            ; // User is not found.
            if (profile == null)
            {
                return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotFound, HttpMessages.UserNotFound)));
            }

            // Initialize access token.
            var token = new TokenViewModel();

            token.LifeTime = 3600;
            token.Type     = "Bearer";

            if (string.IsNullOrWhiteSpace(profile.AccessToken))
            {
                // Add expired time.
                var expiredAt = DateTime.UtcNow.AddSeconds(token.LifeTime);

                var payload = new Dictionary <string, string>();
                payload.Add(ClaimTypes.Email, profile.Email);
                payload.Add(ClaimTypes.Name, $"{profile.FirstName} {profile.LastName}");
                payload.Add(ClaimTypes.Expired, expiredAt.ToString("yyyy/MM/dd"));
                profile.AccessToken = token.AccessToken = _tokenService.Encode(payload);
                _profileCacheService.Add(profile.Email, profile, token.LifeTime);
            }
            else
            {
                token.AccessToken = profile.AccessToken;
            }

            return(Ok(token));
        }
示例#2
0
        public IHttpActionResult Login([FromBody] LoginViewModel info)
        {
            #region Parameters validation

            if (info == null)
            {
                info = new LoginViewModel();
                Validate(info);
            }

            #endregion

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            #region Find account information in database

            // Hash the password first.
            var hashedPassword = _encryptionService.InitMd5(info.Password).ToLower();

            // Find accounts from db
            var accounts = UnitOfWork.RepositoryStudent.Search();

            accounts = accounts.Where(x =>
                                      x.Username.Equals(info.Username, StringComparison.InvariantCultureIgnoreCase) &&
                                      x.Status == MasterItemStatus.Active);

            //            // Find account availability.
            //            var account = await accounts.FirstOrDefaultAsync();
            //            if (account == null)
            //                return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotFound,
            //                    HttpMessages.AccountNotFound));

            // Find roles related to user.
            var userRoles = UnitOfWork.RepositoryUserRole.Search();

            var userRolesPairs = (from user in accounts
                                  from userRole in userRoles
                                  where userRole.StudentId == user.Id
                                  select new
            {
                User = user,
                UserRole = userRole
            }).ToList();

            var profile = new LoginModel
            {
                User  = userRolesPairs.Select(x => x.User).FirstOrDefault(),
                Roles = userRolesPairs.Select(x => x.UserRole.RoleId).ToList()
            };

            // User is not found in database.
            if (profile.User == null)
            {
                return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotFound,
                                                                   HttpMessages.AccountNotFound)));
            }

            // Check user role
            if (profile.Roles == null || profile.Roles.Count < 1)
            {
                return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Forbidden,
                                                                   HttpMessages.NoRoleAssignedToUser)));
            }

            // Check Password
            if (!hashedPassword.Equals(profile.User.Password, StringComparison.InvariantCultureIgnoreCase))
            {
                return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotFound,
                                                                   HttpMessages.AccountNotFound)));
            }

            #region Token initialization

            // Initiate claim.
            //var generic = new Generic(account);

            var claims = new Dictionary <string, string>
            {
                { nameof(profile.User.Id), profile.User.Id.ToString() },
                { nameof(profile.User.Username), profile.User.Username },
                { nameof(profile.User.Fullname), profile.User.Fullname }
            };

            var token = new TokenViewModel();
            token.Code       = IdentityService.EncodeJwt(claims, IdentityService.JwtSecret);
            token.Expiration = SystemTimeService.DateTimeUtcToUnix(DateTime.Now.AddSeconds(IdentityService.JwtLifeTime));
            token.LifeTime   = IdentityService.JwtLifeTime;

            // Convert user information to profile.
            var cachedProfile = AutoMapper.Mapper.Map <Database.Models.Entities.Student, ProfileViewModel>(profile.User);
            cachedProfile.Roles = profile.Roles;

            // Push information back to cache.
            _profileCacheService.Add(cachedProfile.Id, cachedProfile);

            #endregion

            return(Ok(token));

            #endregion
        }