Example #1
0
        public async Task <IActionResult> GetProfile()
        {
            var identity = User.Identity;

            if (identity == null)
            {
                return(Forbid());
            }
            var userId = identity.Name;

            var user = await RavenDatabaseProvider.GetEntity <User>(userId);

            if (user == null)
            {
                return(Forbid());
            }
            var userDto = new OutputUserProfileDto
            {
                Id           = user.Id,
                FirstName    = user.FirstName,
                LastName     = user.LastName,
                Type         = user.Type,
                Email        = user.Email,
                DateCreated  = user.DateCreated,
                DateModified = user.DateModified
            };

            return(Ok(userDto));
        }
Example #2
0
        // Save refresh-token
        public override async Task ApplyTokenResponse(ApplyTokenResponseContext context)
        {
            if (context.Response.Error == null && context.Response.RefreshToken != null)
            {
                if (context.Request.IsRefreshTokenGrantType())
                {
                    var refreshTokenId = RefreshTokenProvider.GenerateId(context.Request.RefreshToken);
                    await RavenDatabaseProvider.DeleteEntity(refreshTokenId);
                }

                string remoteIpAddress = context.HttpContext.Connection.RemoteIpAddress?.ToString();
                string userAgent       = null;
                if (context.HttpContext.Request.Headers.ContainsKey("User-Agent"))
                {
                    userAgent = context.HttpContext.Request.Headers["User-Agent"].ToString();
                }
                await RefreshTokenProvider.CreateAsync(
                    context.Ticket.Principal.Identity.Name,
                    context.Response.RefreshToken,
                    remoteIpAddress,
                    userAgent,
                    context.Options.RefreshTokenLifetime);
            }
            return;
        }
Example #3
0
        public async Task <IActionResult> GetInfo([FromBody] InputUsersDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var users = new List <User>();

            foreach (var id in dto.Ids)
            {
                var user = await RavenDatabaseProvider.GetEntity <User>(id);

                if (user != null)
                {
                    users.Add(user);
                }
            }

            var result = new OutputUsersDto
            {
                Users = users
            };

            return(Ok(result));
        }
Example #4
0
        // Validate the grant_type and the client application credentials
        public override async Task ValidateTokenRequest(ValidateTokenRequestContext context)
        {
            // Reject the token requests that don't use grant_type=password or grant_type=refresh_token.
            if (!context.Request.IsPasswordGrantType() && !context.Request.IsRefreshTokenGrantType())
            {
                context.Reject(
                    error: OpenIdConnectConstants.Errors.UnsupportedGrantType,
                    description: "Only grant_type=password or grant_type=refresh_token are accepted by this server.");

                return;
            }

            // Check if refresh-token exists in DB
            if (context.Request.IsRefreshTokenGrantType())
            {
                var id = RefreshTokenProvider.GenerateId(context.Request.RefreshToken);
                if (!await RavenDatabaseProvider.IsEntityExists(id))
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidClient,
                        description: "Invalid client.");
                    return;
                }
            }

            // Since there's only one application and since it's a public client
            // (i.e a client that cannot keep its credentials private), call Skip()
            // to inform the server the request should be accepted without
            // enforcing client authentication.
            context.Skip();
            return;
        }
Example #5
0
        public async Task ResetAccessFailedCountAsync(LoginDetails entity)
        {
            entity.DateLockoutEndsUtc = null;
            entity.AccessFailedCount  = 0;

            await RavenDatabaseProvider.UpdateEntity(entity.Id, entity);
        }
Example #6
0
        public async Task <LoginDetails> GetEntity(string uniqueId)
        {
            var loginProviderId = GenerateId(uniqueId);
            var entity          = await RavenDatabaseProvider.GetEntity <LoginDetails>(loginProviderId);

            return(entity);
        }
Example #7
0
 public async Task AccessFailedAsync(LoginDetails entity)
 {
     entity.AccessFailedCount++;
     if (entity.AccessFailedCount >= AccessFailedMaxCount)
     {
         entity.DateLockoutEndsUtc = DateTime.UtcNow.Add(LockoutTime);
     }
     await RavenDatabaseProvider.UpdateEntity(entity.Id, entity);
 }
 public async Task CreateAsync(string userId, string refreshToken, string remoteIpAddress, string userAgent, TimeSpan refreshTokenLifetime)
 {
     var id     = GenerateId(refreshToken);
     var entity = new RefreshTokenDetails
     {
         Id           = id,
         UserId       = userId,
         RefreshToken = refreshToken,
         DateCreated  = DateTime.UtcNow,
         IpAddress    = remoteIpAddress,
         UserAgent    = userAgent,
         DateExpires  = DateTime.UtcNow + refreshTokenLifetime
     };
     await RavenDatabaseProvider.CreateEntity(entity);
 }
Example #9
0
        public async Task <IActionResult> Bootstrap()
        {
            try
            {
                RavenDatabaseProvider.EnsureDatabaseExists("smartbudget", true);

                InputUserRegistrationDto dto = new InputUserRegistrationDto
                {
                    FirstName       = "Admin",
                    LastName        = "Developer",
                    Email           = "*****@*****.**",
                    Password        = "******",
                    ConfirmPassword = "******"
                };

                var userLoginId = LoginProvider.GenerateId(dto.Email);

                var user = new User
                {
                    FirstName   = dto.FirstName,
                    LastName    = dto.LastName,
                    Email       = dto.Email,
                    CreatedBy   = "System",
                    DateCreated = DateTime.UtcNow,
                    Type        = UserType.Admin
                };
                await RavenDatabaseProvider.CreateEntity(user);

                var loginDetails = new LoginDetails
                {
                    Id          = userLoginId,
                    UniqueId    = dto.Email,
                    UserId      = user.Id,
                    CreatedBy   = "System",
                    DateCreated = DateTime.UtcNow
                };
                LoginProvider.SetPassword(loginDetails, dto.Password);
                await RavenDatabaseProvider.CreateEntity(loginDetails);

                return(Ok("Setup configurado com sucesso!"));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Example #10
0
        public async Task <IActionResult> Register([FromBody] InputUserRegistrationDto dto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }
                var userLoginId = LoginProvider.GenerateId(dto.Email);
                if (await RavenDatabaseProvider.IsEntityExists(userLoginId))
                {
                    return(BadRequest($"{nameof(dto.Email)} already exists."));
                }

                var user = new User
                {
                    FirstName   = dto.FirstName,
                    LastName    = dto.LastName,
                    Email       = dto.Email,
                    CreatedBy   = "System",
                    DateCreated = DateTime.UtcNow
                };
                await RavenDatabaseProvider.CreateEntity(user);

                var loginDetails = new LoginDetails
                {
                    Id          = userLoginId,
                    UniqueId    = dto.Email,
                    UserId      = user.Id,
                    CreatedBy   = "System",
                    DateCreated = DateTime.UtcNow
                };
                LoginProvider.SetPassword(loginDetails, dto.Password);
                await RavenDatabaseProvider.CreateEntity(loginDetails);

                return(Ok());
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Example #11
0
        public async Task <IActionResult> GetList()
        {
            var users = await RavenDatabaseProvider.GetEntities <User>();

            return(Ok(users.Select(x => x.Id)));
        }
Example #12
0
        // Implementing HandleTokenRequest to issue an authentication ticket containing the user claims
        public override async Task HandleTokenRequest(HandleTokenRequestContext context)
        {
            // Only handle grant_type=password requests and let ASOS
            // process grant_type=refresh_token requests automatically.
            if (context.Request.IsPasswordGrantType())
            {
                // Get user login data.
                var loginDetails = await LoginProvider.GetEntity(context.Request.Username);

                if (loginDetails == null)
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Invalid credentials.");
                    return;
                }
                if (loginDetails.UniqueId != context.Request.Username)
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Invalid credentials.");
                    return;
                }

                // Get user data
                var user = await RavenDatabaseProvider.GetEntity <User>(loginDetails.UserId);

                if (user == null)
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Invalid username or password.");
                    return;
                }
                // Ensure the user is allowed to sign in.
                if (await UserProvider.IsBannedAsync(user))
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "The specified user is not allowed to sign in.");
                    return;
                }

                // Ensure the user is not already locked out.
                if (LoginProvider.SupportsUserLockout && await LoginProvider.IsLockedOutAsync(loginDetails))
                {
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Invalid credentials.");
                    return;
                }

                // Ensure the password is valid.
                if (!LoginProvider.IsPasswordCorrect(loginDetails, context.Request.Password))
                {
                    if (LoginProvider.SupportsUserLockout)
                    {
                        // Increment lock out count
                        await LoginProvider.AccessFailedAsync(loginDetails);
                    }
                    context.Reject(
                        error: OpenIdConnectConstants.Errors.InvalidGrant,
                        description: "Invalid credentials.");
                    return;
                }
                if (LoginProvider.SupportsUserLockout)
                {
                    // Reset lock out data
                    await LoginProvider.ResetAccessFailedCountAsync(loginDetails);
                }

                var identity = new ClaimsIdentity(OpenIdConnectServerDefaults.AuthenticationScheme);

                // Note: the subject claim is always included in both identity and
                // access tokens, even if an explicit destination is not specified.
                identity.AddClaim(OpenIdConnectConstants.Claims.Subject, loginDetails.UserId);

                // Add user-id
                identity.AddClaim(ClaimTypes.Name, user.Id,
                                  OpenIdConnectConstants.Destinations.AccessToken);

                // Add user-role
                identity.AddClaim(ClaimTypes.Role, user.Type.ToString(),
                                  OpenIdConnectConstants.Destinations.AccessToken);

                // Create a new authentication ticket holding the user identity.
                var ticket = new AuthenticationTicket(
                    new ClaimsPrincipal(identity),
                    new AuthenticationProperties(),
                    OpenIdConnectServerDefaults.AuthenticationScheme);

                // Set the list of scopes granted to the client application.
                // (specify offline_access to issue a refresh token).
                ticket.SetScopes(OpenIdConnectConstants.Scopes.OfflineAccess);

                context.Validate(ticket);
            }

            return;
        }