예제 #1
0
        public async Task <AuthOutput> Authenticate(string password, string loginName, string secretKey, int validPeriodInMinutes)
        {
            var failed = new AuthOutput
            {
                Result = AuthMessage.AuthFailed
            };

            try
            {
                var query = from a in _userRepo.GetAll()
                            join b in _roleAssignmentRepo.GetAll() on a.Id equals b.UserId
                            join c in _permissionRepo.GetAll() on b.RoleId equals c.RoleId
                            where a.LoginName == loginName && !a.IsDeleted && !b.IsDeleted && !c.IsDeleted
                            select new
                {
                    User           = a,
                    RoleAssignment = b,
                    Claim          = c
                };
                var output = await query.ToListAsync();

                if (output.Count == 0)
                {
                    return(failed);
                }

                var credential     = output.First().User;
                var computedHashPw = _crypytoHelper.GenerateHashedPassword(password, credential.Salt);
                if (credential.PasswordHash != computedHashPw)
                {
                    return(failed);
                }

                return(new AuthOutput
                {
                    Result = AuthMessage.AuthSuccess,
                    DisplayName = credential.DisplayName,
                    JwToken = _tokenHelper.GenerateJwToken(credential.Id, secretKey, validPeriodInMinutes),
                    Permissions = output.Select(x => x.Claim.Claim).ToList(),
                    UserId = credential.Id,
                    RoleId = output.First().RoleAssignment.RoleId
                });
            }
            catch (InvalidOperationException)
            {
                return(failed);
            }
            catch (Exception e)
            {
                throw e;
            }
        }