Esempio n. 1
0
        public IActionResult Login([FromBody] LoginRequestModel login)
        {
            var status = _userRepository.FindUser(login.Username, login.Password);

            if (status.Message != Strings.OK)
            {
                return(StatusCode(403, new { message = status.Message }));
            }

            string role = Enum.GetName(typeof(Role), status.User.Role);

            return(Ok(new { access_token = _jwt.GenerateToken(login.Username, role), user = status.User }));
        }
        public ActionResult Register([FromBody] RegisterRequest request)
        {
            dynamic result = Repository.Register(request);

            if (result == null)
            {
                return(NotFound(new { message = "not found" }));
            }
            if (result.ToString() == "Password not matching")
            {
                return(BadRequest(new { message = "Password not matching" }));
            }
            else if (result.ToString() == "This email is already used")
            {
                return(BadRequest(new { message = "This email is already used" }));
            }
            else if (result.ToString() == "Email format incorrect")
            {
                return(BadRequest(new { message = "Email format incorrect" }));
            }
            else if (result.ToString() == "Field cannot be empty")
            {
                return(BadRequest(new { message = "Field cannot be empty" }));
            }
            else if (result.ToString() == "Error")
            {
                return(BadRequest(new { message = "Error" }));
            }

            return(Ok(new { token = Jwt.GenerateToken(result) }));
        }
Esempio n. 3
0
        public async Task <IActionResult> SigninAsync([FromBody] SigninDto signinDto, [FromServices] IValidator <SigninDto> validator)
        {
            var validated = await validator.ValidateAsync(signinDto);

            if (!validated.IsValid)
            {
                return(BadRequest(validated.Errors.Select(e => new { message = e.ErrorMessage, statusCode = e.ErrorCode }).Distinct()));
            }

            var result = await _authService.AuthenticateAsync(signinDto);

            // busca no cache
            if (!result.Succeeded)
            {
                return(BadRequest(new { message = "Invalid e-mail or password", StatusCode = 401 }));
            }

            // generate token
            var user = await _authService.FindAsync(signinDto);

            user.Last_Login = DateTime.Now;

            var data = _mapper.Map <UserDto>(user);

            return(Ok(new {
                message = "user logged!",
                Token = _jwt.GenerateToken(user).AccessToken,
                StatusCode = 200,
                Data = data
            }));
        }
Esempio n. 4
0
        public async Task <ActionResult <ApiResponse <LoginResponse> > > Login([FromBody] ApiRequest <LoginRequest> request)
        {
            try
            {
                var user = await this._usersDm
                           .GetByAsync(
                    email : request.Data.Email,
                    password : request.Data.Password);

                if (user != null)
                {
                    /* Agregar token con JWT */
                    var token = Jwt.GenerateToken(
                        secret: this._appSettings.Secret,
                        issuer: this._appSettings.Issuer,
                        audience: this._appSettings.Audience,
                        expirationInMinutes: int.Parse(this._appSettings.TokenExpirationInMinutes),
                        claims: new List <Claim>
                    {
                        new Claim("UserId", user.Id.ToString()),
                        new Claim("Email", user.Email)
                    });
                    var expiresInTicks = Jwt.GetExpiresTokenInTicks(int.Parse(this._appSettings.TokenExpirationInMinutes));

                    return(Ok(new ApiResponse <LoginResponse>
                    {
                        Result = new LoginResponse
                        {
                            Token = token,
                            ExpiresToken = expiresInTicks
                        },
                        Error = null,
                        Status = HttpStatusCode.OK
                    }));
                }
                else
                {
                    return(NotFound(new ApiResponse
                    {
                        Error = "User not found",
                        Status = HttpStatusCode.NotFound
                    }));
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Error users/login");
                return(BadRequest(new ApiResponse
                {
                    Error = e.Message,
                    Status = HttpStatusCode.BadRequest
                }));
            }
        }
Esempio n. 5
0
        private async Task GenerateJwt(CancellationToken stoppingToken)
        {
            try
            {
                PracticeInfo practiceInfo;
                var          filePath = Path.GetFullPath(@"practiceinfo.json");
                if (File.Exists(filePath))
                {
                    var fileText = File.ReadAllText(filePath);
                    practiceInfo = JsonConvert.DeserializeObject <PracticeInfo>(fileText);
                }
                else
                {
                    await ConnectToBoxUi(stoppingToken);

                    _logger.LogInformation("[SyncService] Getting TPM DeviceId...");
                    var deviceInfo = await _boxUiHubConnection.InvokeAsync <DeviceInfoDto>("GetDeviceId");

                    _tpmDeviceId = deviceInfo.DeviceId;

                    // Retrieve requested box
                    var box = await _registryManager.GetTwinAsync(_tpmDeviceId);

                    _logger.LogInformation($"Received box info from azure {box.Tags}");
                    if (!box.Tags.Contains("practiceid"))
                    {
                        _logger.LogInformation($"No Practice ID found in tags {box.Tags}");
                        return;
                    }

                    practiceInfo = new PracticeInfo
                    {
                        PracticeId  = box.Tags["practiceid"],
                        DoctorId    = box.Tags["doctorid"],
                        DoctorEmail = box.Tags["doctoremail"]
                    };
                    _pracId = practiceInfo.PracticeId;

                    using (var writer = File.CreateText(filePath))
                    {
                        await writer.WriteAsync(JsonConvert.SerializeObject(practiceInfo));
                    }
                }
                _pracId = practiceInfo.PracticeId;
                _myJwt  = Jwt.GenerateToken(practiceInfo.DoctorEmail, practiceInfo.DoctorId, practiceInfo.PracticeId, _configuration["JwtKey"],
                                            _configuration["JwtExpireDays"], _configuration["JwtIssuer"]);
                _jwtLife = DateTime.Now.AddDays(Convert.ToInt32(_configuration["JwtExpireDays"]));
                _logger.LogInformation($"[SyncService] assigned token: SUCCESS");
            }
            catch (Exception e)
            {
                _logger.LogError($"[SyncService] GenerateJwt Exception: {e}");
            }
        }
Esempio n. 6
0
        public ActionResult <Response> Login(dataLogin data)
        {
            try
            {
                if (string.IsNullOrEmpty(data.userName))
                {
                    return(new Response(-9, "Bạn chưa nhập tên đăng nhập"));
                }

                if (string.IsNullOrEmpty(data.passWord))
                {
                    return(new Response(-10, "Bạn chưa nhập mật khẩu"));
                }

                var status = 0;
                data.userName = data.userName.ToLower();
                AdminModel _user = _adminAccess.Login(data.userName, Encrypt.Md5(data.passWord), ref status);

                if (status > 0)
                {
                    var tokenKey = _jwtAuthen.GenerateToken(_user);
                    _user.token = new Token
                    {
                        tokenKey    = tokenKey,
                        timeExpried = _appSetting.TokenExpire
                    };

                    return(new Response(status, "Đăng nhập thành công", _user));
                }
                if (status == -1)
                {
                    return(new Response(-1, "Tài khoản của bạn chưa đăng ký trên hệ thống"));
                }
                if (status == -2)
                {
                    return(new Response(-2, "Mật khẩu không chính xác"));
                }
                if (status == -3)
                {
                    return(new Response(-3, "Tài khoản của bạn đã bị khóa"));
                }

                return(new Response("Đăng nhập thất bại"));
            }
            catch (Exception e)
            {
                NLogLogger.Error(string.Format("CheckLogin: {0}", e.ToString()));
                return(new Response(e.ToString()));
            }
        }
Esempio n. 7
0
        public IActionResult CreateToken(JwtRequest login)
        {
            IActionResult response = Unauthorized();

            var loginResult = _userRegistrationService.ValidateUser(_userSettings.UsernamesEnabled ? login.username : login.username, login.password);

            if (loginResult == UserLoginResults.Successful)
            {
                var user = _userService.GetUserByUsername(login.username);

                var tokenString = Jwt.GenerateToken(user);
                response = Ok(new { token = tokenString });
            }

            return(response);
        }
Esempio n. 8
0
        public async Task <AuthenticateResponse> Authenticate(AuthenticateRequest req)
        {
            var userQuery = await _users.FindAsync(usr => usr.Username == req.Username);

            var user = userQuery.ToList().FirstOrDefault();

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

            if (!PasswordHash.Verify(req.Password, user.Password))
            {
                return(null);
            }

            var token = Jwt.GenerateToken(_jwtSettings, user);

            return(new AuthenticateResponse(user, token));
        }
Esempio n. 9
0
        public async Task <UserDto> Authenticate(string username, string password)
        {
            if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
            {
                throw new ArgumentException("Username or password not provided!");
            }

            IEnumerable <User> users = await UnitOfWork.Repository <User>().GetAsync(x => x.Username == username || x.Email == username, includeProperties: "Roles,Roles.Role");

            User user = users.FirstOrDefault(x => Hash.Validate(password, x.Salt, x.Password));

            if (user == null)
            {
                throw new UnauthorizedAccessException("Invalid username or password!");
            }

            Jwt.GenerateToken(user, options);

            return(new UserDto().MapFromEntity(user));
        }
Esempio n. 10
0
        public ActionResult Login([FromBody] LoginRequest request)
        {
            dynamic result = Repository.Login(request);

            if (result == null)
            {
                return(NotFound(new { message = "not found" }));
            }

            if (result.ToString() == "Error")
            {
                return(BadRequest(new { message = "Error" }));
            }

            if (result == "Not Matching")
            {
                return(BadRequest(new { message = "Not matching" }));
            }

            return(Ok(new { token = Jwt.GenerateToken(result) }));
        }
Esempio n. 11
0
        public Task <string> Login(LoginModel model)
        {
            try
            {
                var hashedPassword = Hasher.CreatePasswordHash(model.Email, model.Password);
                var reseller       = _repository.Retrieve(x => x.Email == model.Email).SingleOrDefault();

                if (reseller == null || reseller.Password != hashedPassword)
                {
                    throw new CashbackServiceException(Messages.LoginOrPassInvalid);
                }

                _logger.LogInformation($"[AuthenticationService/Login] Token requisitado para {model.Email}");
                return(Task.FromResult(Jwt.GenerateToken(_configuration["TokenJWT:Issuer"], _configuration["TokenJWT:Audience"], DateTime.Now.AddMinutes(int.Parse(_configuration["TokenJWT:DurationMinutes"])), _configuration["TokenJWT:Key"])));
            }
            catch (Exception ex)
            {
                _logger.LogError($"[AuthenticationService/Login] {ex.Message}", ex);
                throw ex;
            }
        }
Esempio n. 12
0
        public async Task <CreateUserResponse> Create(CreateUserRequest req)
        {
            var query1 = await _users.FindAsync(usr => usr.Username == req.Username);

            if (query1.ToList().FirstOrDefault() != null)
            {
                throw new Exception("Username already in use");
            }

            var query2 = await _users.FindAsync(usr => usr.Email == req.Email);

            if (query2.ToList().FirstOrDefault() != null)
            {
                throw new Exception("Email already in use");
            }

            var user = new User(req);
            await _users.InsertOneAsync(user);

            var token = Jwt.GenerateToken(_jwtSettings, user);

            return(new CreateUserResponse(user, token));
        }