Example #1
0
        public async Task <IActionResult> Login(UserForLoginDTO userdto)
        {
            //throw new Exception("this is the exception");

            var user = await rep.Login(userdto.UserName, userdto.Password);

            if (user == null)
            {
                return(Unauthorized());
            }

            var claims = new[] {
                new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, userdto.UserName)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config.GetSection("AppSettings:Token").Value));

            var cred = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDiscriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = cred
            };

            var tokenhandler = new JwtSecurityTokenHandler();
            var token        = tokenhandler.CreateToken(tokenDiscriptor);
            var mainPhotoUrl = user.Photos.FirstOrDefault(e => e.IsMain);

            return(Ok(new
            {
                token = tokenhandler.WriteToken(token),
                mainphotourl = mainPhotoUrl?.Url
            }));
        }
        public async Task <IActionResult> Login(UserForLoginDTO userForLoginDTO)
        {
            var userFromRepo = await this.repositry.Login(userForLoginDTO.UserName.ToLower(), userForLoginDTO.PassWord);

            if (userFromRepo == null) // user dosn`t exisits in database
            {
                return(Unauthorized());
            }
            else
            {
                var claims = new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                    new Claim(ClaimTypes.Name, userFromRepo.UserName),
                };

                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.config.GetSection("AppSettings:Token").Value));

                // SecurityAlgorithms.HmacSha512Signature => security algo ussing to hashing
                var Credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject            = new ClaimsIdentity(claims),
                    Expires            = DateTime.Now.AddDays(1),
                    SigningCredentials = Credentials
                };

                var tokenHandler = new JwtSecurityTokenHandler();

                var token = tokenHandler.CreateToken(tokenDescriptor);
                return(Ok(new
                {
                    token = tokenHandler.WriteToken(token)
                }));
            }
        }
        public async Task <IActionResult> Login(UserForLoginDTO userForLoginDTO)
        {
            var userfromrepo = await _repo.Login(userForLoginDTO.Username.ToLower(), userForLoginDTO.Password);

            if (userfromrepo != null)
            {
                var claims = new ClaimsIdentity();
                claims.AddClaim(new Claim(ClaimTypes.NameIdentifier, userfromrepo.Id.ToString()));
                claims.AddClaim(new Claim(ClaimTypes.Name, userfromrepo.Username));
                claims.AddClaim(new Claim(ClaimTypes.Role, userfromrepo.Role));

                var key       = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(_config.GetSection("Appsettings").GetSection("Token").Value));
                var key1      = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("ProEMLh5e_qnzdNU"));
                var signature = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

                var tokendescription = new SecurityTokenDescriptor()
                {
                    Subject            = claims,
                    SigningCredentials = signature,
                    Expires            = DateTime.Now.AddDays(1),
                    //  EncryptingCredentials=new EncryptingCredentials(key1, SecurityAlgorithms.Aes128KW,
                    //SecurityAlgorithms.Aes128CbcHmacSha256)
                };


                var tokenhandler = new JwtSecurityTokenHandler();
                var token        = tokenhandler.CreateJwtSecurityToken(tokendescription);
                return(Ok(new
                {
                    JWTtoken = tokenhandler.WriteToken(token)
                }));
            }
            else
            {
                return(Unauthorized());
            }
        }
Example #4
0
        public async Task <IActionResult> Login(UserForLoginDTO userForLoginDTO)
        {
            var userFromRepo = await _repo.Login(userForLoginDTO.Username.ToLower(), userForLoginDTO.Password);

            if (userFromRepo == null)
            {
                return(Unauthorized());
            }

            var claims = new[]
            {
                new Claim(ClaimTypes.NameIdentifier, userFromRepo.Id.ToString()),
                new Claim(ClaimTypes.Name, userFromRepo.Username)
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:Token").Value));

            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = creds
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);

            var user = _mapper.Map <UserForListDTO>(userFromRepo);

            return(Ok(new {
                token = tokenHandler.WriteToken(token),
                user
            }));
        }
        public async Task <IActionResult> Login(UserForLoginDTO user)
        {
            var loggedInUser = await _repo.Login(user.Email, user.Password);

            if (loggedInUser == null)
            {
                return(Unauthorized());
            }

            var claims = new[] {
                new Claim(ClaimTypes.NameIdentifier, loggedInUser.Id.ToString()),
                new Claim(ClaimTypes.Name, loggedInUser.UserName),
                new Claim(ClaimTypes.Email, loggedInUser.Email)
            };
            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config.GetSection("AppSettings:JWTKEY").Value));

            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject            = new ClaimsIdentity(claims),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = credentials
            };

            var tokenHandler = new JwtSecurityTokenHandler();

            var token = tokenHandler.CreateToken(tokenDescriptor);



            return(Ok(new
            {
                token = tokenHandler.WriteToken(token)
            }));
        }
Example #6
0
        public async void Login_ReturnsOkObjectResult()
        {
            using (var mock = AutoMock.GetLoose())
            {
                // Arrange
                var user = new UserForLoginDTO();

                mock.Mock <IAuthService>()
                .Setup(service => service.Login(user))
                .Returns(() =>
                {
                    return(Task.FromResult(new User()));
                });

                // DI happens at this step
                var controller = mock.Create <AuthController>();

                // Act
                var response = await controller.Login(user);

                // Assert
                Assert.IsType <OkObjectResult>(response);
            }
        }
        public IDataResult <User> Login(UserForLoginDTO userForLoginDto)
        {
            var userToCheckResult = _userService.GetByMail(userForLoginDto.Email);

            if (!userToCheckResult.Success)
            {
                return(new ErrorDataResult <User>(userToCheckResult.Message));
            }

            var userToCheck = userToCheckResult.Data;

            if (userToCheck == null)
            {
                return(new ErrorDataResult <User>(Messages.UserNotFound));
            }

            if (!HashingHelper.VerifyPasswordHash(userForLoginDto.Password, userToCheck.PasswordHash,
                                                  userToCheck.PasswordSalt))
            {
                return(new ErrorDataResult <User>(Messages.PasswordError));
            }

            return(new SuccessDataResult <User>(userToCheck, Messages.SuccessfulLogin));
        }
Example #8
0
        public async Task <IActionResult> Login(UserForLoginDTO userForLoginDto)
        {
            //throw new Exception("Computer Says No!!");

            var user = await _userManager.FindByNameAsync(userForLoginDto.Username);

            var result = await _signInManager.CheckPasswordSignInAsync(user, userForLoginDto.Password, false);

            if (result.Succeeded)
            {
                var appUser = await _userManager.Users.FirstOrDefaultAsync(u => u.NormalizedUserName == userForLoginDto.Username.ToUpper());

                var userToReturn = _mapper.Map <UserForDetailDTO>(appUser);

                return(Ok(new
                {
                    token = GenerateJWTToken(appUser).Result,
                    user = userToReturn
                }));
            }


            return(Unauthorized());
        }
Example #9
0
        public async Task <IActionResult> Login([FromBody] UserForLoginDTO user)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Model invalid"));
            }
            //check for valid
            var userFromDb = await _authService.LogIn(user);

            if (userFromDb == null)
            {
                return(NoContent());
            }

            //generate token
            var userToken = await _authService.GenerateToken(userFromDb,
                                                             _configuration.GetSection("AuthKey:Token").Value);

            return(Ok(new
            {
                userToken,
                userFromDb
            }));
        }
Example #10
0
        public async Task <UserDataDTO> Login(UserForLoginDTO userForLoginDto)
        {
            var user = await _userManager.FindByNameAsync(userForLoginDto.UserName);

            var result = await _signInManager.CheckPasswordSignInAsync(user, userForLoginDto.Password, false);

            if (result.Succeeded)
            {
                var appUser = await _userManager.Users.FirstOrDefaultAsync(x => x.NormalizedUserName == userForLoginDto.UserName.ToUpper());

                var claims = GetClaims(user);

                return(new UserDataDTO
                {
                    UserToReturnDTO = new UserToReturnDTO {
                        Id = user.Id,
                        UserName = user.UserName
                    },
                    Token = await _jwtTokenService.GenerateJwtToken(claims)
                });
            }

            throw new UnauthorizedException("Invalid creidentionals");
        }
Example #11
0
 public async Task <ActionResult <LoginServiceModel> > Login(UserForLoginDTO model)
 {
     return(await this.authentication
            .LoginAsync(model)
            .ToActionResult());
 }
Example #12
0
        public async Task <IActionResult> Login(UserForLoginDTO userForLoginDTO)
        {
            try
            {
                var userFromRepo = await _repo.Login(userForLoginDTO.UserName.ToLower(), userForLoginDTO.Password);

                if (userFromRepo == null)
                {
                    return(BadRequest("Credenciales Invalidas")); // Unauthorized();
                }

                if (!userFromRepo.IsActive)
                {
                    return(BadRequest("Usuario Bloqueado, contacte al Administrador."));
                }

                var memberDb = await _repoGym.GetMember(userFromRepo.UserName, null, 0);

                // if (string.IsNullOrEmpty(userFromRepo.PhotoUrl))
                // {
                //     //TODO: This must be removed...
                //     userFromRepo.PhotoUrl = "http://majahide-001-site1.itempurl.com/releasecandidates/PhotosManagerAPI/prometheusmedia/SIQBICPROFILES/UserProfiles/nopic.jpg";
                // }

                /*
                 * var userData = new {
                 *  role = userFromRepo.Role.DisplayName,
                 *  membershipExpiration = memberDb.MembershipExpiration,
                 *  photoUrl = memberDb.PhotoUrl,
                 *  packageId = memberDb.MembershipTypeActiveId
                 * };
                 */
                // uri foto
                // role role
                // version paquete
                // expiration

                var claims = new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, memberDb.User.Id.ToString()),
                    new Claim(ClaimTypes.Email, userFromRepo.UserName),
                    new Claim(ClaimTypes.Name, userFromRepo.DisplayName) //,
                    //new Claim(ClaimTypes.Uri, memberDb.PhotoUrl == null ? "" : memberDb.PhotoUrl),
                    //new Claim(ClaimTypes.Role, userFromRepo.Role.DisplayName),
                    //new Claim(ClaimTypes.Version, memberDb.MembershipTypeActiveId == null ? "0" : memberDb.MembershipTypeActiveId.ToString()),
                    //new Claim(ClaimTypes.Expiration, memberDb.MembershipExpiration.ToString("yyyy-MM-dd"))

                    //new Claim(ClaimTypes.UserData,  JsonConvert.SerializeObject(userData))
                    // , new Claim(ClaimTypes.Webpage, userFromRepo.PhotoUrl)
                };


                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this._config.GetSection("AppSettings:Token").Value));

                var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512Signature);

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(claims),
                    //Expires = DateTime.Now.AddDays(1),
                    SigningCredentials = creds
                };

                var tokenHandler = new JwtSecurityTokenHandler();

                var token = tokenHandler.CreateToken(tokenDescriptor);

                return(Ok(new
                {
                    token = tokenHandler.WriteToken(token),
                    role = userFromRepo.Role.DisplayName,
                    membershipExpiration = memberDb.MembershipExpiration,
                    photoUrl = memberDb.PhotoUrl,
                    packageId = memberDb.MembershipTypeActiveId == null ? 0 : memberDb.MembershipTypeActiveId,
                    memberId = memberDb.MemberId
                }));
                // return Ok(token);
            } catch (Exception ex)
            {
                new FileManagerHelper().RecordLogFile(MethodBase.GetCurrentMethod().ReflectedType.FullName, userForLoginDTO, ex);
                return(BadRequest(this._appSettings.Value.ServerError));
            }
        }
Example #13
0
 public async Task <SignInResult> LoginSucceeded(UserForLoginDTO userForLoginDto)
 =>
 _signInManager.CheckPasswordSignInAsync(await FindUserByUserName(userForLoginDto.Email),
                                         userForLoginDto.Password, false).Result;
        public async Task <IActionResult> Login([FromBody] UserForLoginDTO userForLoginDto)
        {
            var result = await _userService.Login(userForLoginDto);

            return(Ok(result));
        }