コード例 #1
0
        public async Task <IActionResult> RegisterTeacher([FromBody] TeacherRegisterVM model)
        {
            return(await HandleRequestAsync(async() =>
            {
                string imageName = Path.GetRandomFileName() + ".jpg";
                var filePath = Path.Combine(Directory.GetCurrentDirectory(), @"wwwroot\Uploaded\Users");

                string pathSaveImages = InitStaticFiles
                                        .CreateImageByFileName(_env, _configuration,
                                                               new string[] { Directory.GetCurrentDirectory(), @"wwwroot", "Uploaded", "Users" },
                                                               imageName,
                                                               model.Photo);

                //+38 (098) 665 34 18
                model.Photo = imageName;

                var rezult = await _teacherService.Create(model);
                if (rezult)
                {
                    var user = _userManager.FindByEmailAsync(model.Email).Result;
                    var teacher = await _teacherService.GetTeacherById(user.Id);
                    JwtInfo jwtInfo;
                    if (teacher != null)
                    {
                        // Return token
                        jwtInfo = new JwtInfo()
                        {
                            Token = _jwtTokenService.CreateToken(user),
                            RefreshToken = _jwtTokenService.CreateRefreshToken(user),
                            SchoolId = teacher.SchoolId.ToString()
                        };
                    }
                    else
                    {
                        // Return token
                        jwtInfo = new JwtInfo()
                        {
                            Token = _jwtTokenService.CreateToken(user),
                            RefreshToken = _jwtTokenService.CreateRefreshToken(user),
                        };
                    }

                    this._logger.LogDebug("End method LoginUser...");

                    return Ok(jwtInfo);
                }
                else
                {
                    var invalid = new Dictionary <string, string>
                    {
                        { "email", "Користувач з даною електронною поштою уже зареєстрований" }
                    };
                    return BadRequest(invalid);
                }
            }));
        }
コード例 #2
0
        public async Task <IActionResult> Login([FromBody] Credentials credentials)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new { invalid = "Problem validation" }));
            }

            var result = await _signInManager
                         .PasswordSignInAsync(credentials.Email, credentials.Password,
                                              false, false);

            if (!result.Succeeded)
            {
                return(BadRequest(new { invalid = "Не правильно введені дані!" }));
            }

            var user = await _userManager.FindByEmailAsync(credentials.Email);

            await _signInManager.SignInAsync(user, isPersistent : false);

            return(Ok(
                       new
            {
                token = _jWTTokenService.CreateToken(user),
                refToken = _jWTTokenService.CreateRefreshToken(user)
            }));
        }
コード例 #3
0
        public async Task <IActionResult> Google([FromBody] GoogleAuthViewModel model)
        {
            var userInfo = GoogleJsonWebSignature.ValidateAsync(model.TokenId, new GoogleJsonWebSignature.ValidationSettings()).Result;

            var user = await _userManager.FindByEmailAsync(userInfo.Email);

            if (user == null)
            {
                string path = _fileService.UploadAccountImage(userInfo.Picture);

                user = new DbUser
                {
                    FirstName  = userInfo.GivenName,
                    LastName   = userInfo.FamilyName,
                    Email      = userInfo.Email,
                    UserName   = userInfo.Email,
                    SignUpTime = DateTime.Now,
                    AvatarUrl  = path
                };

                var result = await _userManager.CreateAsync(user, RandomPasswordGenerator.GenerateRandomPassword());

                if (!result.Succeeded)
                {
                    var errors = CustomValidator.GetErrorsByIdentityResult(result);
                    return(BadRequest(errors));
                }
                var roleName   = "User";
                var roleresult = _roleManager.CreateAsync(new DbRole
                {
                    Name = roleName
                }).Result;

                result = _userManager.AddToRoleAsync(user, roleName).Result;

                var invalid = new Dictionary <string, string>
                {
                    { "googleInvalid", "Error google login." }
                };

                if (!result.Succeeded)
                {
                    return(BadRequest(invalid));
                }
            }
            else
            {
                _fileService.UploadAccountImageIfNotExists(user, userInfo.Picture);
            }

            await _signInManager.SignInAsync(user, isPersistent : false);

            return(Ok(
                       new
            {
                token = _jWTTokenService.CreateToken(user),
                refToken = _jWTTokenService.CreateRefreshToken(user)
            }));
        }
コード例 #4
0
        public async Task <IActionResult> LoginUser([FromBody] LoginDTO loginModel)
        {
            // Auto return errors from viewModel and other global errors
            return(await HandleRequestAsync(async() =>
            {
                int countOfAttempts = this.HttpContext.Session.GetInt32("LoginAttemts") ?? 0;
                countOfAttempts++;
                this.HttpContext.Session.SetInt32("LoginAttemts", countOfAttempts);

                this._logger.LogDebug("Start method LoginUser...");
                var result = await _signInManager.PasswordSignInAsync(loginModel.Email, loginModel.Password, false, false);
                if (!result.Succeeded)
                {
                    return BadRequest(new InvalidData
                    {
                        Invalid = "Не правильно введені дані",
                        ShowCaptcha = countOfAttempts > 4 ? true : false
                    });
                }

                var user = await _userManager.FindByEmailAsync(loginModel.Email);
                await _signInManager.SignInAsync(user, isPersistent: false);

                if (countOfAttempts > 4)
                {
                    // TODO: Captcha validation
                    this._recaptchaService.IsValid(loginModel.RecaptchaToken);
                }


                // Return token
                JwtInfo jwtInfo = new JwtInfo()
                {
                    Token = _jwtTokenService.CreateToken(user),
                    RefreshToken = _jwtTokenService.CreateRefreshToken(user)
                };

                this.HttpContext.Session.SetInt32("LoginAttemts", 0);
                this._logger.LogDebug("End method LoginUser...");

                return Ok(jwtInfo);
            }));
        }
コード例 #5
0
        public async Task <IActionResult> Login([FromBody] LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                var errors = CustomValidator.GetErrorsByModel(ModelState);
                return(BadRequest(errors));
            }

            var user = _context.Users.FirstOrDefault(u => u.Email == model.Email);

            if (user == null)
            {
                return(BadRequest(new { invalid = "Користувача із вказаними обліковими даними не знайдено" }));
            }

            var result = _signInManager
                         .PasswordSignInAsync(user, model.Password, false, false).Result;

            if (!result.Succeeded)
            {
                return(BadRequest(new { invalid = "Користувача із вказаними обліковими даними не знайдено" }));
            }

            var block = _context.UserAccessLocks.FirstOrDefault(u => u.Id == user.Id);

            if (block != null)
            {
                return(BadRequest(new { invalid = "Нажаль Вас Заблоковано" }));
            }

            await _signInManager.SignInAsync(user, isPersistent : false);

            return(Ok(
                       new
            {
                token = _tokenService.CreateToken(user),
                refToken = _tokenService.CreateRefreshToken(user)
            }));
        }
コード例 #6
0
        public async Task <IActionResult> Facebook([FromBody] FacebookAuthViewModel model)
        {
            // 1.generate an app access token
            var appAccessTokenResponse = await Client.GetStringAsync($"https://graph.facebook.com/oauth/access_token?client_id={_fbAuthSettings.AppId}&client_secret={_fbAuthSettings.AppSecret}&grant_type=client_credentials");

            var appAccessToken = JsonConvert.DeserializeObject <FacebookAppAccessToken>(appAccessTokenResponse);

            // 2. validate the user access token
            var userAccessTokenValidationResponse = await Client.GetStringAsync($"https://graph.facebook.com/debug_token?input_token={model.AccessToken}&access_token={appAccessToken.AccessToken}");

            var userAccessTokenValidation = JsonConvert.DeserializeObject <FacebookUserAccessTokenValidation>(userAccessTokenValidationResponse);

            if (!userAccessTokenValidation.Data.IsValid)
            {
                return(BadRequest(new { invalid = "Invalid facebook token!" }));
            }

            // 3. we've got a valid token so we can request user data from fb
            var userInfoResponse = await Client.GetStringAsync($"https://graph.facebook.com/v2.8/me?fields=id,email,first_name,last_name,name,gender,locale,birthday,picture&access_token={model.AccessToken}");

            var userInfo = JsonConvert.DeserializeObject <FacebookUserData>(userInfoResponse);

            // 4. ready to create the local user account (if necessary) and jwt
            var user = await _userManager.FindByEmailAsync(userInfo.Email);

            if (user == null)
            {
                string path = _fileService.UploadAccountImage(userInfo.Picture.Data.Url);

                user = new DbUser
                {
                    FirstName  = userInfo.FirstName,
                    LastName   = userInfo.LastName,
                    Email      = userInfo.Email,
                    UserName   = userInfo.Email,
                    SignUpTime = DateTime.Now,
                    AvatarUrl  = path
                };

                var result = await _userManager.CreateAsync(user, RandomPasswordGenerator.GenerateRandomPassword());

                if (!result.Succeeded)
                {
                    var errors = CustomValidator.GetErrorsByIdentityResult(result);
                    return(BadRequest(errors));
                }
                var roleName   = "User";
                var roleresult = _roleManager.CreateAsync(new DbRole
                {
                    Name = roleName
                }).Result;

                result = _userManager.AddToRoleAsync(user, roleName).Result;

                var invalid = new Dictionary <string, string>
                {
                    { "facebookInvalid", "Error facebook login." }
                };

                if (!result.Succeeded)
                {
                    return(BadRequest(invalid));
                }
            }
            else
            {
                _fileService.UploadAccountImageIfNotExists(user, userInfo.Picture.Data.Url);
            }

            await _signInManager.SignInAsync(user, isPersistent : false);

            return(Ok(
                       new
            {
                token = _jWTTokenService.CreateToken(user),
                refToken = _jWTTokenService.CreateRefreshToken(user)
            }));
        }