public async Task <IActionResult> AddNewCompetitor([FromBody] IServices.Request.AddCompetitor competitor)
        {
            List <string> errors = new List <string>();


            var code = _identityDbContext.AuthorizationCode.Where(x => x.Key == competitor.confirmationCode).FirstOrDefault();

            if (code != null)
            {
                errors.Add("Code Already Exist");
            }
            else
            {
                int result = await _codeService.CreateCode(competitor);

                if (result == -1)
                {
                    errors.Add("Legue Not Exist");
                }
                else if (result < 0)
                {
                    errors.Add("Unknow Error");
                }
                else
                {
                    AuthorizationCode authorization = new AuthorizationCode
                    {
                        Key          = competitor.confirmationCode,
                        CompetitorId = result
                    };

                    await _identityDbContext.AddAsync(authorization);

                    await _identityDbContext.SaveChangesAsync();
                }
            }
            if (errors.Count == 0)
            {
                UserViewModel userViewModel = new UserViewModel
                {
                    Status = "Succes"
                };
                return(Ok(userViewModel));
            }
            else
            {
                UserViewModel userViewModel = new UserViewModel
                {
                    Status = "Error",
                    Errors = errors.ToArray()
                };
                return(BadRequest(userViewModel));
            }
        }
Esempio n. 2
0
        public async Task <ActionResult <string> > SignIn(SignInRequest request)
        {
            if (await CheckUserExist(request.Email))
            {
                return(BadRequest("login занят"));
            }

            var userCreateRequest = _mapper.Map <CreateUserRequest>(request);

            var user = Entities.User.Create(userCreateRequest);
            await _dbContext.AddAsync(user);

            await _dbContext.SaveChangesAsync();

            return("Регистрация прошла успешно");
        }
        public async Task <IActionResult> RegisterAsync([FromBody] RegisterModel input)
        {
            // Пароль для упрощения храниться в чистом виде!
            // В реальных проектах, необходимо хранить пароль в виде хэша с солью.

            if (!await _context.Users.AnyAsync(x => x.Login == input.Login))
            {
                var user = new IdentityUser
                {
                    Login    = input.Login,
                    Email    = input.Email,
                    Password = input.Password
                };

                await _context.AddAsync(user);

                await _context.SaveChangesAsync();

                return(Ok(user.Id));
            }

            return(BadRequest("User already exist."));
        }
Esempio n. 4
0
        public async ValueTask <string> CreateJwtTokenAsync(TUser user, string displayName = null)
        {
            if (user.Id == default)
            {
                user = await _userManager.FindAsync(user);
            }
            if (user is null || user.Id == default)
            {
                throw new Exception("user not found");
            }
            if (!_identityOptions.AllowMultipleLogins)
            {
                if (_jwtIdentityDb.AccessTokens.ToArray().Any(token => token.UserId == user.Id))
                {
                    throw new Exception("this user has logged in before");
                }
            }
            var accessToken = new AccessToken()
            {
                Id                 = Guid.NewGuid(),
                ExpiresTime        = DateTime.Now.Add(_identityOptions.ValidityTime),
                UserId             = user.Id,
                LastLoginTime      = DateTime.Now,
                LastLoginIp        = _context.Connection.RemoteIpAddress.ToString(),
                LastLoginUserAgent = _context.Request.Headers["User-Agent"][0]
            };

            accessToken = (await _jwtIdentityDb.AddAsync(accessToken)).Entity;
            await _jwtIdentityDb.SaveChangesAsync();

            //return accessToken.Id.ToString();

            var keyProvider = new KeyProvider(_identityOptions.SecretKey, KeySize._256);
            var issuer      = _identityOptions.Issuer ?? "";

            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.NameIdentifier, user.UserName, ClaimValueTypes.String, issuer),
                new Claim(JwtRegisteredClaimNames.Jti, accessToken.Id.ToString(), ClaimValueTypes.String, issuer),
                new Claim(JwtRegisteredClaimNames.Iss, issuer, ClaimValueTypes.String, issuer),
                new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.Now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64, issuer),
            };

            if (displayName != null)
            {
                claims.Add(new Claim(ClaimTypes.Name, displayName, ClaimTypes.Name, issuer));
            }
            claims.AddRange(_jwtIdentityDb.UserRoles
                            .Where(ur => ur.UserId == user.Id)
                            .Select(ur => new Claim(ClaimTypes.Role, ur.Role.Name)));
            var key   = new SymmetricSecurityKey(keyProvider.GetNextKey(256));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
            var now   = DateTime.Now;
            var encryptingCredentials = new EncryptingCredentials(new SymmetricSecurityKey(keyProvider.Key.ToArray()),
                                                                  SecurityAlgorithms.Aes256KW, SecurityAlgorithms.Aes256CbcHmacSha512);
            var descriptor = new SecurityTokenDescriptor
            {
                Audience = _identityOptions.Audience,
                EncryptingCredentials = _identityOptions.UseEncryption ? encryptingCredentials : null,
                Expires            = now.Add(_identityOptions.ValidityTime),
                IssuedAt           = now,
                Issuer             = issuer,
                NotBefore          = now,
                SigningCredentials = creds,
                Subject            = new ClaimsIdentity(claims),
            };
            var tokenHandler  = new JwtSecurityTokenHandler();
            var securityToken = tokenHandler.CreateToken(descriptor);
            var tokenStr      = new JwtSecurityTokenHandler().WriteToken(securityToken);

            keyProvider.Dispose();
            return(tokenStr);
        }