Esempio n. 1
0
        public async Task <ServiceResult <UserServiceModel> > UpdateAsync(int id, UserUpdateModel info, IEnumerable <Claim> userClaims)
        {
            int   userId   = Convert.ToInt32(userClaims.FirstOrDefault(claim => claim.Type == ClaimTypes.NameIdentifier)?.Value);
            Roles userRole = (Roles)Convert.ToInt32(userClaims.FirstOrDefault(claim => claim.Type == ClaimTypes.Role)?.Value);

            if (userId != id)
            {
                if (userRole != Roles.Admin)
                {
                    return(new ServiceResult <UserServiceModel>(ServiceResultStatus.ActionNotAllowed, "You cannot update this user"));
                }
            }

            UserInDbModel user = await database.GetAsync(id);

            if (user == null)
            {
                return(new ServiceResult <UserServiceModel>(ServiceResultStatus.ItemNotFound, "User cannot be found"));
            }

            bool IsPasswordSame = protector.VerifyPassword(new HashedPasswordWithSalt {
                Password = user.HashedPassword, Salt = user.Salt
            }, info.Password ?? "");
            HashedPasswordWithSalt hashSalt = protector.ProtectPassword(info.Password ?? "");

            UserInDbModel newUser = new UserInDbModel(
                id,
                info.Login ?? user.Login,
                info.Nickname ?? user.Nickname,
                info.Role == default ? user.Role : (int)info.Role,
                IsPasswordSame ? user.Salt : hashSalt.Salt,
                IsPasswordSame ? user.HashedPassword : hashSalt.Password
                );

            await database.UpdateAsync(id, newUser);

            return(new ServiceResult <UserServiceModel>(ServiceResultStatus.ItemChanged));
        }
        public async Task <ServiceResult <TokenJwt> > LogInAsync(string login, string password)
        {
            UserInDbModel user = await database.GetUserByLoginAsync(login);

            if (user == null)
            {
                return(new ServiceResult <TokenJwt>(ServiceResultStatus.IncorrectLoginPassword));
            }

            if (!protection.VerifyPassword(new HashedPasswordWithSalt {
                Salt = user.Salt, Password = user.HashedPassword
            }, password))
            {
                return(new ServiceResult <TokenJwt>(ServiceResultStatus.IncorrectLoginPassword));
            }

            return(new ServiceResult <TokenJwt>(ServiceResultStatus.ItemRecieved,
                                                new TokenJwt(
                                                    GetIdentity(mapper.Map <UserClaimsModel, UserInDbModel>(user)),
                                                    365,
                                                    "UNBELIEVABLEsecretKEEEEEYYYYYY!!!!!=)",
                                                    "http://localhost:44338/",
                                                    "TaskServer")));
        }