示例#1
0
        public async Task <IActionResult> Login([FromBody] UserEntity user)
        {
            if (user == null)
            {
                return(BadRequest());
            }
            var userEmail = await _userService.FinByEmail(user.Email);

            if (userEmail == null)
            {
                return(NotFound());
            }
            try
            {
                var token = await TokenHelpers.GenerateJWT(userEmail, _config["Jwt:Key"], _config["Jwt:Issuer"]);

                Response.Cookies.Append("X-Access-Token", token, new CookieOptions()
                {
                    HttpOnly = true, SameSite = SameSiteMode.Strict
                });
                Response.Cookies.Append("X-Username", userEmail.UserName, new CookieOptions()
                {
                    HttpOnly = true, SameSite = SameSiteMode.Strict
                });

                return(Ok(token));
            }
            catch
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, user));
            }
        }
        //Post api/user/Login
        public async Task <IActionResult> PostLogin([FromForm] UserLoginModel model)
        {
            var IsInfoValid = ModelState.IsValid;

            if (IsInfoValid == false)
            {
                return(BadRequest(new { message = "Login Info not valid" }));
            }
            var key  = Encoding.UTF8.GetBytes(_AppSetting.JWT_Secret);
            var User = await _userManager.FindByNameAsync(model.UserName);

            if (User == null)
            {
                return(NotFound());
            }
            if (User.IsActive == false)
            {
                return(NotFound());
            }
            var role = await _userManager.GetRolesAsync(User);

            if (User != null && await _userManager.CheckPasswordAsync(User, model.Password))
            {
                var Token    = TokenHelpers.CreateToken(User, key);
                var userrole = role;
                return(Ok(new { Token, userrole }));
            }
            else
            {
                return(BadRequest(new { message = "Login Info not valid" }));
            }
        }
 public AuthController(
     IDistributedCache cache,
     IConfiguration config,
     ILogger <AuthController> logger,
     TokenHelpers helpers)
 {
     _cache   = cache;
     _config  = config;
     _logger  = logger;
     _helpers = helpers;
 }
示例#4
0
        protected async override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            IToken token = TokenHelpers.GetRefreshToken();

            var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, _authUri);

            httpRequestMessage.Headers.Add("appid", _appId);
            HttpResponseMessage httpResponseMessage;

            // Determine what type of token request to make (if needed) based on tracking
            // the timestamps of the access token and the state of the local token
            switch (token.TokenRequestType)
            {
            case TokenRequestType.None:
                break;

            case TokenRequestType.ClientCredential:

                httpResponseMessage = await PrimaryTokenRequest(httpRequestMessage, cancellationToken);

                string authResponse = await httpResponseMessage.Content.ReadAsStringAsync();

                token = JsonConvert.DeserializeObject <AuthResponse>(authResponse);
                token.Save();
                break;

            case TokenRequestType.RefreshToken:

                httpResponseMessage = await RefreshTokenRequest(httpRequestMessage, token.RefreshToken, cancellationToken);

                string jsonResponse = await httpResponseMessage.Content.ReadAsStringAsync();

                token = JsonConvert.DeserializeObject <AuthResponse>(jsonResponse);

                // The refresh token request failed - try the primary token
                if (!httpResponseMessage.IsSuccessStatusCode)
                {
                    httpResponseMessage = await PrimaryTokenRequest(httpRequestMessage, cancellationToken);

                    token = JsonConvert.DeserializeObject <AuthResponse>(await httpResponseMessage.Content.ReadAsStringAsync());
                }

                token.Save();
                break;
            }

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);
            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

            return(response);
        }
示例#5
0
        public IActionResult Post([FromBody] User value)
        {
            if (value == null)
            {
                throw SLExceptionManager.Wrap(new ArgumentNullException(nameof(value), "L'argument ne peut pas être NULL."));
            }

            IActionResult response = Unauthorized();

            var user = new User();

            if (user != null)
            {
                response = Ok(value: new { token = TokenHelpers.BuildUserToken(value) });
            }

            return(response);
        }
示例#6
0
        public async Task <JsonResult> Token([FromBody] TokenModel model)
        {
            if (!string.IsNullOrEmpty(model.AccessToken))
            {
                var handler = new JwtSecurityTokenHandler();
                var token   = handler.ReadJwtToken(model.AccessToken);
                var now     = DateTime.UtcNow;

                if (now >= token.ValidTo)
                {
                    var userId    = token.Claims.FirstOrDefault().Value;
                    var intUserId = int.Parse(userId);

                    var dbUser = await _dbContext.Users.FirstOrDefaultAsync(x => x.Id == intUserId)
                                 .ConfigureAwait(false);

                    var dbToken = await _dbContext.Tokens.FirstOrDefaultAsync(x => x.Id == dbUser.TokenId)
                                  .ConfigureAwait(false);

                    if (dbToken.RefreshToken == model.RefreshToken)
                    {
                        await TokenHelpers.GenerateToken(userId, dbToken, _dbContext);

                        return(new JsonResult(new TokenResponse
                        {
                            access_token = dbToken.AccessToken,
                            refresh_token = dbToken.RefreshToken,
                            expired_in = (dbToken.TokenExpiredDate - now).TotalSeconds
                        }));
                    }
                    else
                    {
                        throw new Exception("Неверный Refresh Token");
                    }
                }
                else
                {
                    throw new Exception("Срок действия вашего токена ещё не истёк");
                }
            }

            throw new Exception("Срок действия вашего токена ещё не истёк");
        }
        public void BuildMutation(MutationRoot mutationRoot)
        {
            mutationRoot.Field <AutoRegisteringObjectGraphType <RefreshTokenResultModel> >(
                "refreshToken",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "authenticationToken"
            },
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "refreshToken"
            }),
                resolve: context =>
            {
                var accountService = _contextAccessor.HttpContext.RequestServices.GetRequiredService <IAccountService>();

                return(accountService.RefreshToken(context.GetArgument <string>("authenticationToken"),
                                                   context.GetArgument <string>("refreshToken")));
            }
                );

            mutationRoot.Field <AutoRegisteringObjectGraphType <LoginResultModel> >(
                "login",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "username"
            }, new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "password"
            }),
                resolve: context =>
            {
                var accountService = _contextAccessor.HttpContext.RequestServices.GetRequiredService <IAccountService>();

                return(accountService.LoginAsync(new LoginModel
                {
                    UserName = context.GetArgument <string>("username"),
                    Password = context.GetArgument <string>("password")
                }));
            }
                );

            mutationRoot.Field <AutoRegisteringObjectGraphType <LoginResultModel> >(
                "register",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "email"
            },
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "username"
            },
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "password"
            }),
                resolve: context =>
            {
                var accountService = _contextAccessor.HttpContext.RequestServices.GetRequiredService <IAccountService>();

                return(accountService.RegisterAsync(new RegisterModel
                {
                    UserName = context.GetArgument <string>("username"),
                    Password = context.GetArgument <string>("password"),
                    Email = context.GetArgument <string>("email")
                }));
            }
                );


            mutationRoot.Field <AutoRegisteringObjectGraphType <UserModel> >(
                "createUser",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "email"
            },
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "fullName"
            },
                    new QueryArgument <NonNullGraphType <ListGraphType <StringGraphType> > > {
                Name = "roles"
            }),
                resolve: context =>
            {
                var accountService = _contextAccessor.HttpContext.RequestServices.GetRequiredService <IUserService>();

                return(accountService.CreateUserAsync(new CreateUserModel
                {
                    Roles = context.GetArgument <string[]>("roles"),
                    FullName = context.GetArgument <string>("fullName"),
                    Email = context.GetArgument <string>("email"),
                }));
            }
                ).AuthorizeWith("AdminPolicy");


            mutationRoot.Field <BooleanGraphType>(
                "editUser",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <IntGraphType> > {
                Name = "id"
            },
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "fullName"
            },
                    new QueryArgument <NonNullGraphType <ListGraphType <StringGraphType> > > {
                Name = "roles"
            },
                    new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "email"
            }),
                resolve: context =>
            {
                var accountService = _contextAccessor.HttpContext.RequestServices.GetRequiredService <IUserService>();

                return(accountService.UpdateUserAsync(context.GetArgument <int>("id"), new CreateUserModel
                {
                    Roles = context.GetArgument <string[]>("roles"),
                    FullName = context.GetArgument <string>("fullName"),
                    Email = context.GetArgument <string>("email"),
                }));
            }
                ).AuthorizeWith("AdminPolicy");


            mutationRoot.Field <BooleanGraphType>(
                "deleteUser",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <IntGraphType> > {
                Name = "id"
            }),
                resolve: context =>
            {
                var accountService = _contextAccessor.HttpContext.RequestServices.GetRequiredService <IUserService>();
                var u = TokenHelpers.GetCurrentUsername(_contextAccessor.HttpContext);
                return(accountService.DeleteUserAsync(context.GetArgument <int>("id"), u));
            }
                ).AuthorizeWith("AdminPolicy");
        }
示例#8
0
        public async Task <IActionResult> SignIn([FromBody] SignInModel model)
        {
            // Валидация
            if (string.IsNullOrEmpty(model.login.Trim()) || string.IsNullOrEmpty(model.pass.Trim()))
            {
                throw new Exception(TextResource.Auth_EmptyValues);
            }

            if (model.login.Length < 5 || model.login.Length > 20)
            {
                throw new Exception(TextResource.Auth_LoginWrongLength);
            }

            if (model.pass.Length < 4 || model.pass.Length > 30)
            {
                throw new Exception(TextResource.Auth_PassWrongLength);
            }

            var dbUser = await _dbContext.Users.FirstOrDefaultAsync(x => x.Login == model.login)
                         .ConfigureAwait(false);

            if (dbUser == null)
            {
                throw new Exception("Неправильный логин или пароль");
            }

            var password = PasswordHelpers.EncryptPassword(model.pass, dbUser.Pass.Salt);

            if (!PasswordHelpers.SlowEquals(password, dbUser.Pass.Password))
            {
                throw new Exception("Неправильный логин или пароль");
            }

            var now = DateTime.UtcNow;

            var user = new
            {
                dbUser.Id,
                dbUser.Login,
                dbUser.FirstName,
                dbUser.MiddleName,
                dbUser.Surname,
                dbUser.Email,
                dbUser.BirthDate,
                dbUser.City
            };

            var dbToken = await _dbContext.Tokens.FirstOrDefaultAsync(x => x.Id == dbUser.TokenId)
                          .ConfigureAwait(false);

            if (dbToken != null && dbToken.TokenExpiredDate >= now)
            {
                return(new JsonResult(new SignInResponse
                {
                    access_token = dbToken.AccessToken,
                    refresh_token = dbToken.RefreshToken,
                    expired_in = (dbToken.TokenExpiredDate - now).TotalSeconds,
                    user = user
                }));
            }

            bool isFirst = false;

            // Если пользователь авторизуется впервые
            if (dbToken == null)
            {
                dbToken = new Token();
                isFirst = true;
            }

            await TokenHelpers.GenerateToken(dbUser.Id.ToString(), dbToken, _dbContext, isFirst)
            .ConfigureAwait(false);

            dbUser.TokenId = dbToken.Id;

            await _dbContext.SaveChangesAsync(true)
            .ConfigureAwait(false);

            return(new JsonResult(new SignInResponse
            {
                access_token = dbToken.AccessToken,
                refresh_token = dbToken.RefreshToken,
                expired_in = (dbToken.TokenExpiredDate - now).TotalSeconds,
                user = user
            }));
        }
示例#9
0
        public async Task <IActionResult> Register([FromBody] RegisterUserDto model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new ResponseModel()
                {
                    Message = "Model State is not valid",
                    Result = false,
                    Status = 400
                }));
            }

            if (!IsValidEmail(model.Email))
            {
                return(BadRequest(new ResponseModel()
                {
                    Message = "Please provide a valid email",
                    Result = false,
                    Status = 404
                }));
            }


            if (_userService.IsEmailExist(model.Email))
            {
                return(BadRequest(new ResponseModel()
                {
                    Message = "This email address has been take it please try another one",
                    Status = 404,
                    Result = false
                }));
            }


            // Hash Password
            byte[] passwordHash, passwordSalt;
            HashingHelper.CreatePasswordHash(model.Password, out passwordHash, out passwordSalt);

            User user = new User()
            {
                Email        = model.Email,
                PasswordHash = passwordHash,
                PasswordSalt = passwordSalt,
                Address      = model.Address,
                IsActive     = false,
                Name         = model.Name,
                Surname      = model.Surname,
                Phone        = model.Phone,
                Role         = Role.User,
                ImageUrl     = "profile.png"
            };

            await _userService.CreateAsync(user);



            // send Email

            TokenHelpers tokenHelpers = new TokenHelpers(_configuration);

            string VerificationToken = tokenHelpers.GenerateVerificationToken(model.Email);

            string url = _configuration.Value.FrontUrl + "/verifyAccount?token=" + VerificationToken;

            string body = $"Please click <a href = {url} >link</a> link to verify YourAccount";


            await _emailService.SendMail("Verify Account", body, model.Email);

            //
            return(Ok(new
            {
                Message = "User has been created successfully",
                Result = true,
                Status = 200,
            }));
        }
示例#10
0
        public async Task <IActionResult> Login([FromBody] LoginUserDto model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new ResponseModel()
                {
                    Message = "Model State is not valid",
                    Result = false,
                    Status = 400
                }));
            }


            if (!IsValidEmail(model.Email))
            {
                return(BadRequest(new ResponseModel()
                {
                    Message = "Please provide a valid email",
                    Result = false,
                    Status = 404
                }));
            }

            var user = _userService.GetByEmail(model.Email);

            if (user == null)
            {
                return(BadRequest(new ResponseModel()
                {
                    Message = "User Not Found",
                    Status = 404,
                    Result = false
                }));
            }
            TokenHelpers tokenHelpers = new TokenHelpers(_configuration);

            if (!user.IsActive)
            {
                string VerificationToken = tokenHelpers.GenerateVerificationToken(model.Email);

                string url = _configuration.Value.FrontUrl + "/token=" + VerificationToken;

                string body = $"Please click <a href = {url} >link</a> link to verify YourAccount";


                await _emailService.SendMail("Verify Account", body, model.Email);

                return(BadRequest(new ResponseModel()
                {
                    Message = "Account is not active please active your account. New Activation link has been sent",
                    Status = 404,
                    Result = false
                }));
            }

            if (!HashingHelper.VerifyPasswordHash(model.Password, user.PasswordHash, user.PasswordSalt))
            {
                return(BadRequest(new ResponseModel()
                {
                    Message = "Password is wrong. Try Again.",
                    Result = false,
                    Status = 404
                }));
            }


            TokenResultModel token = tokenHelpers.GenerateToken(user);

            user.LastLoggedInDate = DateTime.Now;

            await _userService.UpdateAsync(user);

            return(Ok(new
            {
                user = new
                {
                    user.Id,
                    user.Name,
                    user.Surname,
                    user.Email,
                    user.Address,
                    role = user.Role.ToString(),
                    user.Phone,
                    user.ImageUrl,
                    user.LastLoggedInDate
                },
                token
            }));
        }
示例#11
0
 public void Build_A_Token_With_User_Is_NULL()
 {
     TokenHelpers.BuildUserToken(null);
 }
        // Post api/user/register
        public async Task <object> PostRegister([FromForm] UserRegisterModel NewUser)
        {
            //to create role
            // MyRoleModel iden = new MyRoleModel
            //{
            //  Name = "Student"
            //};


            //            IdentityResult res = await _roleManager.CreateAsync(iden);
            ////////////////////
            //to get the intake for the user
            //var intake = NewUser.IntakeId;


            ///////////////////////////
            //to get the intakeid
            int intakename = NewUser.IntakeId.GetValueOrDefault();
            var intake     = db.GetIntakeByName(intakename);

            if (intake == null)
            {
                return(NotFound());
            }
            NewUser.IntakeId = intake.IntakeId;

            /////////////////
            var  file            = Request?.Form?.Files?.FirstOrDefault();
            bool IsInfoValid     = ModelState.IsValid;
            bool IsImageUploaded = file?.Length > 0;

            if (IsInfoValid == false)
            {
                return(BadRequest(new { message = "invalid registration info" }));
            }
            if (IsImageUploaded == false)
            {
                //if user exists
                var checkuser = await _userManager.FindByNameAsync(NewUser.UserName);

                if (checkuser != null)
                {
                    return(StatusCode(409, $"User '{NewUser.UserName}' already exists."));
                }
                ///////////
                var user = await _userManager.CreateAsync(NewUser, NewUser.Password);

                // to assign role to user
                var userdata = await _userManager.FindByNameAsync(NewUser.UserName);

                await _userManager.AddToRoleAsync(userdata, "Student");

                //token part
                var keytoken  = Encoding.UTF8.GetBytes(_AppSetting.JWT_Secret);
                var Usertoken = await _userManager.FindByNameAsync(NewUser.UserName);

                await _userManager.AddToRoleAsync(Usertoken, "Student");

                var roletoken = await _userManager.GetRolesAsync(Usertoken);

                if (Usertoken != null && await _userManager.CheckPasswordAsync(Usertoken, NewUser.Password))
                {
                    var Token    = TokenHelpers.CreateToken(Usertoken, keytoken);
                    var userrole = roletoken;
                    return(Ok(new { Token, userrole }));
                }


                return(Ok(user));
            }

            var uploadedfilename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
            var IsImgExtAllowed  = FSHelpers.IsImageExtensionAllowed(uploadedfilename);

            if (IsImgExtAllowed == false)
            {
                return(BadRequest(new { message = "Image extensions allowed are jPG and PNG only " }));
            }
            var dbImagePath = FSHelpers.SaveProfileImage(NewUser, uploadedfilename, file);

            NewUser.PrifleImageUrl = dbImagePath;
            //if user exists
            var checkuser2 = await _userManager.FindByNameAsync(NewUser.UserName);

            if (checkuser2 != null)
            {
                return(StatusCode(409, $"User '{NewUser.UserName}' already exists."));
            }
            ///////////
            var result = await _userManager.CreateAsync(NewUser, NewUser.Password);

            // to assign role to user
            var u = await _userManager.FindByNameAsync(NewUser.UserName);

            var r = await _userManager.AddToRoleAsync(u, "Student");

            //token part
            var key  = Encoding.UTF8.GetBytes(_AppSetting.JWT_Secret);
            var User = await _userManager.FindByNameAsync(NewUser.UserName);

            await _userManager.AddToRoleAsync(User, "Student");

            var role = await _userManager.GetRolesAsync(User);

            if (User != null && await _userManager.CheckPasswordAsync(User, NewUser.Password))
            {
                var Token    = TokenHelpers.CreateToken(User, key);
                var userrole = role;
                return(Ok(new { Token, userrole }));
            }
            else
            {
                return(BadRequest(new { message = "Login Info not valid" }));
            }
        }