Beispiel #1
0
        public async Task <IHttpActionResult> CreateUser(CreateUserBindingModel createUserModel)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (createUserModel == null)
            {
                return(BadRequest("Error. Model is empty"));
            }

            var user = new ApplicationUserDto()
            {
                UserName  = createUserModel.Username,
                Email     = createUserModel.Email,
                FirstName = createUserModel.FirstName,
                LastName  = createUserModel.LastName
            };

            var addUserResult = await userService.CreateAsync(user, createUserModel.Password);

            if (!addUserResult.Succeeded)
            {
                return(GetErrorResult(addUserResult));
            }

            await AssignRolesToUser(user.Id, new[] { "User" });

            var locationHeader = new Uri(Url.Link("GetUserById", new { id = user.Id }));

            return(Created(locationHeader, user));
        }
Beispiel #2
0
        //POST : /api/ApplicationUser/Login
        public async Task <IActionResult> Login(ApplicationUserDto dto)
        {
            var user = await _userManager.FindByNameAsync(dto.UserName);

            if (user != null)
            {
                if (await _userManager.CheckPasswordAsync(user, dto.Password))
                {
                    var claims = await _userManager.GetClaimsAsync(user);

                    var tokenDescriptor = new SecurityTokenDescriptor
                    {
                        Subject            = new ClaimsIdentity(claims),
                        Expires            = DateTime.UtcNow.AddMinutes(30),
                        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSettings.Value.Secret)), SecurityAlgorithms.HmacSha256Signature)
                    };

                    var tokenHandler  = new JwtSecurityTokenHandler();
                    var securityToken = tokenHandler.CreateToken(tokenDescriptor);
                    var token         = tokenHandler.WriteToken(securityToken);
                    return(Ok(new { token }));
                }
                else
                {
                    return(BadRequest("Password is incorrect."));
                }
            }
            else
            {
                return(BadRequest("Username does not exist."));
            }
        }
        public async Task <ApplicationUserDto> RegisterAsync(RegisterDto model)
        {
            var newUser = new ApplicationUser()
            {
                UserName = model.Username
            };

            var result = await _userManager.CreateAsync(newUser, model.Password);

            if (result.Succeeded)
            {
                await _userManager.AddToRoleAsync(newUser, "User");

                var role = await GetRoleAsync(newUser);

                // authentication successful so generate jwt token
                var token = GenerateJwtToken(newUser, role);

                var userDto = new ApplicationUserDto(newUser)
                {
                    Token = token,
                    Role  = role
                };

                return(userDto);
            }
            else
            {
                throw new RegistrationException(string.Join(" ", result.Errors.Select(e => e.Description)));
            }
        }
Beispiel #4
0
 public IActionResult CreateUser([FromBody] ApplicationUserDto user, [FromQuery] string role)
 {
     _log.LogInformation("Called CreateUser");
     try
     {
         ApplicationUser applicationUser = new ApplicationUser {
             UserName = user.UserName
         };
         var result = _userManager.CreateAsync(applicationUser, user.Password).Result;
         if (result.Errors.Any())
         {
             return(new ObjectResult(new ResponseModel <ApplicationUser>(null, result.Errors, "User Could Not Be Created.")));
         }
         var newUser    = _service.GetUserByUserName(user.UserName);
         var roleresult = _userManager.AddToRoleAsync(newUser, role).Result;
         if (result.Errors.Any())
         {
             return(new ObjectResult(new ResponseModel <ApplicationUser>(null, result.Errors, "User was created Successfully But Could Noit Add Role On It.")));
         }
         return(new ObjectResult(new ResponseModel <ApplicationUser>(null, message: "Successfully Created User.")));
     }
     catch (Exception ex)
     {
         _log.LogError(ex.Message);
         return(new ObjectResult(new ResponseModel <ApplicationUser>(null, ex, "Could not create User.")));
     }
 }
Beispiel #5
0
        public async Task <List <ApplicationUserDto> > GetAllUsersCompany(string companyName)
        {
            var usersDto = new List <ApplicationUserDto>();
            var users    = await _userManager.Users.Where(user => user.UserName != "SuperAdmin" && user.Company.Name == companyName).Include(user => user.Company).ToListAsync();

            foreach (var user in users)
            {
                var userDto = new ApplicationUserDto
                {
                    Id       = user.Id,
                    UserName = user.UserName,
                    Company  = new CompanyDto {
                        Id = user.Company.Id, Name = user.Company.Name
                    },
                    Email       = user.Email,
                    PhoneNumber = user.PhoneNumber,
                };
                //РОЛЬ
                var roleName = (await _userManager.GetRolesAsync(user)).FirstOrDefault();
                userDto.RoleName = roleName;
                //КЛЕЙМЫ
                var userClaims = await _userManager.GetClaimsAsync(user);

                if (userClaims.Any())
                {
                    userDto.Claims = userClaims.ToDictionary(claim => claim.Type, claim => claim.Value);
                }
                usersDto.Add(userDto);
            }
            return(usersDto.ToList());
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <param name="id"></param>
        public virtual ApplicationUserDto GetApplicationUserById(String id)
        {
            ApplicationUser    applicationUser = this.ApplicationUserRepository.GetById(id);
            ApplicationUserDto model           = new ApplicationUserDto();

            model.Id            = applicationUser.Id;
            model.CreatedAt     = applicationUser.CreatedAt;
            model.UpdatedAt     = applicationUser.UpdatedAt;
            model.UserName      = applicationUser.UserName;
            model.PasswordHash  = applicationUser.PasswordHash;
            model.PasswordSalt  = applicationUser.PasswordSalt;
            model.NickName      = applicationUser.NickName;
            model.FirstName     = applicationUser.FirstName;
            model.LastName      = applicationUser.LastName;
            model.Sex           = applicationUser.Sex;
            model.Birthday      = applicationUser.Birthday;
            model.Age           = applicationUser.Age;
            model.Phone         = applicationUser.Phone;
            model.Email         = applicationUser.Email;
            model.HeadImageUrl  = applicationUser.HeadImageUrl;
            model.LastLoginTime = applicationUser.LastLoginTime;
            model.LastLoginIP   = applicationUser.LastLoginIP;
            model.Locked        = applicationUser.Locked;
            model.LockedTime    = applicationUser.LockedTime;
            model.Logined       = applicationUser.Logined;
            return(model);
        }
        public virtual void Update(String id, ApplicationUserDto model)
        {
            ApplicationUser applicationUser = this.ApplicationUserRepository.GetById(id);

            applicationUser.CreatedAt     = model.CreatedAt;
            applicationUser.UpdatedAt     = model.UpdatedAt;
            applicationUser.UserName      = model.UserName;
            applicationUser.PasswordHash  = model.PasswordHash;
            applicationUser.PasswordSalt  = model.PasswordSalt;
            applicationUser.NickName      = model.NickName;
            applicationUser.FirstName     = model.FirstName;
            applicationUser.LastName      = model.LastName;
            applicationUser.Sex           = model.Sex;
            applicationUser.Birthday      = model.Birthday;
            applicationUser.Age           = model.Age;
            applicationUser.Phone         = model.Phone;
            applicationUser.Email         = model.Email;
            applicationUser.HeadImageUrl  = model.HeadImageUrl;
            applicationUser.LastLoginTime = model.LastLoginTime;
            applicationUser.LastLoginIP   = model.LastLoginIP;
            applicationUser.Locked        = model.Locked;
            applicationUser.LockedTime    = model.LockedTime;
            applicationUser.Logined       = model.Logined;
            this.ApplicationUserRepository.Update(applicationUser);
        }
Beispiel #8
0
        public async Task <bool> IsUserInRoleAsync(ApplicationUserDto userDto, string roleName)
        {
            var user     = mapper.Map <ApplicationUser>(userDto);
            var isInRole = await userManager.IsInRoleAsync(user, roleName);

            return(isInRole);
        }
        /// <summary>
        /// Simple implementation of user's leveling.
        /// </summary>
        /// <param name="user"></param>
        public UserLevelingResultDto LevelUser(ApplicationUserDto user, EventType eventType)
        {
            var result = new UserLevelingResultDto();
            // Let's do levels as UserLevels 10, 100, 200, 500, 1000, 2000,
            // Collect all combines stats
            int totalStats = user.NumberOfAnswers + user.NumberOfDescriptions + user.NumberOfVotes + user.NumberOfFlags;

            // Check if user's stats are up to date. Would be crazy if they are not.
            if (!user.IsStatisticsCached)
            {
                throw new ServicesException("Can not level user without updated statistics");
            }
            // Check if user's level corresponds to where he is at
            var levels   = GetLevels();
            int newLevel = 0;

            for (int i = 0; i < levels.Length - 1; i++)
            {
                if (totalStats < levels[i])
                {
                    newLevel = i;
                    break;
                }
            }
            if (newLevel > user.Level)
            {
                // User's level changed.
                user.Level         = newLevel;
                result.GainedLevel = true;
                result.Level       = newLevel;
                UpdateUserLevel(user);
            }
            return(result);
        }
        public async Task <Object> PostApllication(ApplicationUserDto applicationUserDto)
        {
            var data   = _applicationUserBusiness.CreateAppUser(applicationUserDto);
            var result = data.Result.Data;

            return(Ok(result));
        }
        public async Task <object> PostApplicationUser(ApplicationUserDto model)
        {
            var userDto = new ApplicationUserDto()
            {
                FirstName   = model.FirstName,
                LastName    = model.LastName,
                PhoneNumber = model.PhoneNumber,
                UserName    = model.Email,
                Email       = model.Email
            };

            var user = _mapper.Map <ApplicationUser>(userDto);

            try
            {
                var result = await _userManager.CreateAsync(user, model.Password);

                return(Ok(result));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
        public async Task <IActionResult> Create(ApplicationUserDto model)
        {
            try
            {
                var user = await _userService.Create(model);

                if (user == null)
                {
                    return(Ok(new ResultModel
                    {
                        Success = false,
                        Message = Constants.Users.CreateAccountFail
                    }));
                }

                return(Ok(new ResultModel
                {
                    Success = true,
                    Message = Constants.Users.CreateAccountSuccess
                }));
            }
            catch (Exception ex)
            {
                return(Ok(new ResultModel
                {
                    Success = false,
                    Message = ex.Message
                }));
            }
        }
Beispiel #13
0
        public async Task GetUserById_ExistingUser_Ok()
        {
            // Arrange
            var adminToRequest = MockApplicationUsers.Get(0);
            var userToFind     = MockApplicationUsers.Get(1);
            var expectedDto    = new ApplicationUserDto(userToFind);
            var path           = $"{Routes.UserRoute}/{userToFind.Id}";
            var token          = await GetToken(adminToRequest);

            _endSystems.SetBearerToken(token);

            // Act
            var response = await _endSystems.Get(path);

            var dto = JsonStringSerializer.GetApplicationUserDto(response.Body);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.Code);
            Assert.Equal(expectedDto.Id, dto.Id);
            Assert.Equal(expectedDto.Email, dto.Email);
            Assert.Equal(expectedDto.Name, dto.Name);

            // Tear down
            _endSystems.Dispose();
        }
        public void CreatedUserCount(ApplicationUserDto creator, IQueryable <ApplicationUserDto> userDtos)
        {
            var query = from u in userDtos
                        where u.CreatedBy.Equals(creator.Email)
                        select u;

            foreach (var i in query)
            {
                if (i.Role.Equals("SuperAdmin"))
                {
                    creator.TotalSuperAdminCreated += 1;
                }

                if (i.Role.Equals("Admin"))
                {
                    creator.TotalAdminCreated += 1;
                }

                if (i.Role.Equals("Client"))
                {
                    creator.TotalClientCreated += 1;
                }
            }

            creator.TotalUsersCreated = creator.TotalClientCreated + creator.TotalAdminCreated + creator.TotalSuperAdminCreated;
        }
        public void UserServiceTests_FindByIds_FindsUsers()
        {
            // Setup
            var setup = new TestSetup();

            var user = new ApplicationUserDto()
            {
                UserId = "A"
            };

            setup.UserService.AddUserToCache(user);

            var result = setup.UserService.FindByIds(new List <string>()
            {
                "A", "1", "222"
            });

            // Only two users should be returned because "222" is not there.
            Assert.Equal(result.Count, 2);

            Assert.Null(setup.UserService.FindByIds(null));

            result = setup.UserService.FindByIds(new List <string>());

            Assert.Equal(result.Count, 0);
        }
Beispiel #16
0
        /// <summary>
        /// This method shows the information of the selected ticket
        /// <example>tickets/Details/1</example>
        /// <example>tickets/Details/4</example>
        /// </summary>
        /// <param name="id">ID of the selected ticket</param>
        /// <returns>Details of the ticket which ID is given</returns>

        public ActionResult Details(int id)
        {
            ShowTicket showTicket = new ShowTicket();

            //Get the current ticket from the database
            string url = "TicketData/FindTicket/" + id;
            HttpResponseMessage response = client.GetAsync(url).Result;

            if (response.IsSuccessStatusCode)
            {
                TicketDto SelectedTicket = response.Content.ReadAsAsync <TicketDto>().Result;
                showTicket.Ticket = SelectedTicket;

                //Get the user/owner of the selected ticket
                url      = "TicketData/GetTicketUser/" + id;
                response = client.GetAsync(url).Result;
                ApplicationUserDto SelectedUser = response.Content.ReadAsAsync <ApplicationUserDto>().Result;
                showTicket.User = SelectedUser;

                //Get the parking spot of the selected ticket
                url      = "TicketData/GetTicketSpot/" + id;
                response = client.GetAsync(url).Result;
                ParkingSpotDto SelectedSpot = response.Content.ReadAsAsync <ParkingSpotDto>().Result;
                showTicket.Spot = SelectedSpot;

                return(View(showTicket));
            }
            else
            {
                return(RedirectToAction("Error"));
            }
        }
        public async Task <string> Handle(LoginUserExternalQuery request, CancellationToken cancellationToken)
        {
            var user = _mapper.Map <ApplicationUserDto>(_mediator.Send(new GetUserByEmailQuery(request.Email), cancellationToken).Result);

            if (user == null)
            {
                var newUser = new ApplicationUserDto()
                {
                    Email          = request.Email,
                    UserName       = request.Email,
                    EmailConfirmed = true
                };

                var result = await _mediator.Send(new CreateUserCommand(newUser, GenerateRandomPassword.SecurePassword()), cancellationToken);

                if (!result.Succeeded)
                {
                    _logger.LogInformation($"LoginUserExternal: {request.Email}: Failed login: Failed to create a local user");
                    throw new InvalidRegisterException("Failed to register account with third party login provider");
                }
            }
            else
            {
                if (user.AccountEnabled)
                {
                    throw new AccountLockedException();
                }
            }

            var claims = _mediator.Send(new GetUserClaimQuery(user), cancellationToken).Result;

            return(_mediator.Send(new GenerateLoginTokenQuery(claims), cancellationToken).Result);;
        }
Beispiel #18
0
        public ActionResult Details(int id)
        {
            ShowApplication ModelView = new ShowApplication();
            //Using the Show Application View Model
            //Find the application by Id from the database
            string url = "ApplicationData/FindApplication/" + id;
            HttpResponseMessage response = client.GetAsync(url).Result;

            //Response 200 code if it is ok
            if (response.IsSuccessStatusCode)
            {
                ApplicationDto SelectedApplication = response.Content.ReadAsAsync <ApplicationDto>().Result;
                ModelView.Application = SelectedApplication;

                //Errors n/a if it is null
                //Associated Application with User
                url      = "ApplicationData/GetUserForApplication/" + id;
                response = client.GetAsync(url).Result;
                ApplicationUserDto SelectedUser = response.Content.ReadAsAsync <ApplicationUserDto>().Result;
                ModelView.ApplicationUser = SelectedUser;

                //Errors n/a if it is null
                //Associated application with Job
                url      = "ApplicationData/GetJobForApplication/" + id;
                response = client.GetAsync(url).Result;
                JobDto SelectedJob = response.Content.ReadAsAsync <JobDto>().Result;
                ModelView.Job = SelectedJob;

                return(View(ModelView));
            }
            else
            {
                return(RedirectToAction("Error"));
            }
        }
        public virtual String Save(ApplicationUserDto model)
        {
            ApplicationUser applicationUser = new ApplicationUser();

            applicationUser.Id            = model.Id;
            applicationUser.CreatedAt     = model.CreatedAt;
            applicationUser.UpdatedAt     = model.UpdatedAt;
            applicationUser.UserName      = model.UserName;
            applicationUser.PasswordHash  = model.PasswordHash;
            applicationUser.PasswordSalt  = model.PasswordSalt;
            applicationUser.NickName      = model.NickName;
            applicationUser.FirstName     = model.FirstName;
            applicationUser.LastName      = model.LastName;
            applicationUser.Sex           = model.Sex;
            applicationUser.Birthday      = model.Birthday;
            applicationUser.Age           = model.Age;
            applicationUser.Phone         = model.Phone;
            applicationUser.Email         = model.Email;
            applicationUser.HeadImageUrl  = model.HeadImageUrl;
            applicationUser.LastLoginTime = model.LastLoginTime;
            applicationUser.LastLoginIP   = model.LastLoginIP;
            applicationUser.Locked        = model.Locked;
            applicationUser.LockedTime    = model.LockedTime;
            applicationUser.Logined       = model.Logined;
            return(this.ApplicationUserRepository.Save(applicationUser));
        }
        public async Task GetAllUsersOrderedByNameAsync_AllInMockAndInOrder()
        {
            // Arrange
            var allIds = MockApplicationUsers.GetAll().Select(w => w.Id).ToHashSet();

            // Act
            var allUsers = (await _service.GetAllUsersOrderedByNameAsync()).ToArray();
            var dtoIds   = allUsers.Select(w => w.Id).ToHashSet();

            // Assert
            Assert.Equal(allIds.Count, dtoIds.Count);
            foreach (var id in dtoIds)
            {
                Assert.Contains(id, allIds);
            }
            var first = true;
            ApplicationUserDto last = null;

            foreach (var dto in allUsers)
            {
                if (first)
                {
                    first = false;
                }
                else
                {
                    Assert.True(string.Compare(dto.Name, last.Name, StringComparison.Ordinal) >= 0);
                }
                last = dto;
            }
        }
        public async Task <Result <object> > CreateApplicationUser(ApplicationUserDto model)
        {
            var applicationUser = new ApplicationUser()
            {
                UserName = model.UserName,
                Email    = model.Email,
                FullName = model.FullName
            };

            try
            {
                var result = await _userManager.CreateAsync(applicationUser, model.Password);

                if (result.Errors.Count() > 0)
                {
                    return(new Result <object>(false, ResultConstant.RecordNotCreated, result));
                }

                return(new Result <object>(true, ResultConstant.RecordCreated, result));
            }
            catch (Exception)
            {
                return(new Result <object>(false, ResultConstant.RecordNotCreated));
            }
        }
        public async Task EditAsync(ApplicationUserDto dto)
        {
            var existingEntity = await _context.Users.FirstOrDefaultAsync(e => e.Id == dto.Id);

            MapDtoToExistingEntity(dto, existingEntity);
            await _context.SaveChangesAsync();
        }
        public IActionResult Get(string username)
        {
            ApplicationUser    user = _userService.GetUser(username);
            ApplicationUserDto dto  = _mapper.Map <ApplicationUserDto>(user);

            return(Ok(dto));
        }
Beispiel #24
0
        /// <summary>
        /// Registers new user with the given <see cref="ApplicationUserDto"/> model.
        /// </summary>
        /// <param name="newUserDto">Data transfer object of the application user.</param>
        /// <param name="password">Password that user typed.</param>
        public async Task <Result <ApplicationUserDto> > RegisterAsync(ApplicationUserDto newUserDto, string password)
        {
            ApplicationUser newUser = new ApplicationUser
            {
                Email    = newUserDto.Email,
                UserName = newUserDto.Email
            };

            var newUserResult = await _userManager.CreateAsync(newUser, password);

            if (newUserResult.Succeeded)
            {
                await _signInManager.SignInAsync(newUser, false);

                newUserDto.Id = newUser.Id;
                return(new Result <ApplicationUserDto>(newUserDto));
            }
            else
            {
                var errorResult = new Result <ApplicationUserDto>(newUserDto);
                foreach (var error in newUserResult.Errors)
                {
                    errorResult.Errors.Add(error.Description);
                }
                return(errorResult);
            }
        }
Beispiel #25
0
        //POST : /api/ApplicationUser/Register
        public async Task <IActionResult> Register(ApplicationUserDto dto)
        {
            var applicationUser = new ApplicationUser()
            {
                UserName = dto.UserName,
                Email    = dto.Email,
            };

            try
            {
                var result = await _userManager.CreateAsync(applicationUser, dto.Password);

                await _userManager.AddClaimAsync(applicationUser, new Claim("UserID", applicationUser.Id.ToString()));

                if (dto.IsAdmin)
                {
                    await _userManager.AddClaimAsync(applicationUser, new Claim(ClaimTypes.Role, "Administrator", ClaimValueTypes.String, _iSSUER));
                }

                return(Ok(result));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.ToString()));
            }
        }
Beispiel #26
0
        /// <summary>
        /// Remove user from this application if it registered.
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task <ApplicationUserDto> Delete(string id)
        {
            try
            {
                ApplicationUserDto applicationUser = await _userManager.FindByIdAsync(id);

                if (applicationUser != null)
                {
                    AspNetUsers    user   = _aguilaContext.AspNetUsers.Where(x => x.Id == id).FirstOrDefault();
                    IdentityResult result = await _userManager.DeleteAsync(applicationUser);

                    if (result.Succeeded)
                    {
                        return(_mapper.Map <AspNetUsers, ApplicationUserDto>(user));
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }
            }
            catch (Exception)
            {
                return(null);
            }
        }
        public async Task <ApplicationUserDto> AuthenticateAsync(LoginDto model)
        {
            var appUser = await _userManager.FindByNameAsync(model.Username);

            if (appUser != null)
            {
                var result = await _signInManager.CheckPasswordSignInAsync(appUser, model.Password, false);

                if (result.Succeeded)
                {
                    // get user roles
                    var role = await GetRoleAsync(appUser);

                    // authentication successful so generate jwt token
                    var token = GenerateJwtToken(appUser, role);

                    var userDto = new ApplicationUserDto(appUser)
                    {
                        Token = token,
                        Role  = role
                    };

                    return(userDto);
                }
            }

            return(null);
        }
Beispiel #28
0
        public async Task <ServiceResult <LoginResponse> > Handle(GetTokenQuery request, CancellationToken cancellationToken)
        {
            ApplicationUserDto user = await _identityService.CheckUserPassword(request.Email, request.Password);

            if (user == null)
            {
                return(ServiceResult.Failed <LoginResponse>(ServiceError.ForbiddenError));
            }

            var authClaims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, user.Id),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            };

            var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:Secret"]));

            var token = new JwtSecurityToken(
                issuer: _configuration["JWT:ValidIssuer"],
                audience: _configuration["JWT:ValidAudience"],
                expires: DateTime.Now.AddDays(90),
                claims: authClaims,
                signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256)
                );

            return(ServiceResult.Success(new LoginResponse
            {
                User = user,
                Token = new JwtSecurityTokenHandler().WriteToken(token)
            }));
        }
Beispiel #29
0
        public async Task <AppNetUserEntity> CreateUser(ApplicationUserDto dto, string password)
        {
            var user = new AppNetUserEntity()
            {
                UserName           = dto.UserName,
                NormalizedUserName = dto.NormalizedUserName,
                Email                = dto.Email,
                EmailConfirmed       = dto.EmailConfirmed,
                PhoneNumber          = dto.PhoneNumber,
                PhoneNumberConfirmed = dto.PhoneNumberConfirmed
            };

            try {
                var result = await _userManager.CreateAsync(user, password);

                if (result.Succeeded)
                {
                    // Add user to new roles
                    // var roleNames = await _roleManager.Roles.Where(x => model.Roles.Contains(x.Id)).Select(x => x.Name).ToArrayAsync();
                    //var res2 = await _userManager.AddToRolesAsync(user.Id, roleNames);
                    return(user);
                }
                else
                {
                    foreach (var error in result.Errors)
                    {
                        //ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            } catch (Exception er) {
                System.Console.WriteLine(er.Message);
            }
            return(null);
        }
Beispiel #30
0
        /// <summary>
        /// Generate Json Web Token Method
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public string GenerateJSONWebToken(ApplicationUserDto user)
        {
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            List <Claim> claims = new List <Claim>()
            {
                new Claim(ClaimTypes.NameIdentifier, user.UserName),
                new Claim(CinemaClaimTypes.UserId, user.Id.ToString())
            };

            foreach (var role in user.UserRoles)
            {
                claims.Add(new Claim(ClaimTypes.Role, role.Role.Name));
            }
            ;

            ClaimsIdentity claimsIdentity = new ClaimsIdentity(claims);

            var token = new JwtSecurityToken(_config["Jwt:Issuer"],
                                             _config["Jwt:Issuer"],
                                             claims,
                                             expires: DateTime.Now.AddMinutes(120),
                                             signingCredentials: credentials);

            return(new JwtSecurityTokenHandler().WriteToken(token));
        }