Exemple #1
0
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var refreshTokenId = Guid.NewGuid().ToString("n");

            if (context.Ticket == null)
            {
                context.Response.StatusCode   = 400;
                context.Response.ContentType  = "application/json";
                context.Response.ReasonPhrase = "invalid refresh token";
                return;
            }

            IRefreshTokenService refreshTokenService = ResolverFactory.GetService <RefreshTokenService>();

            var client = context.OwinContext.Get <Client>("oauth:client");

            var token = new RefreshTokenDto()
            {
                RefreshTokenId = UnitHelper.GetHash(refreshTokenId),
                Subject        = context.Ticket.Identity.Name,
                IssuedUtc      = DateTime.UtcNow,
                ExpiresUtc     = DateTime.UtcNow.AddDays(client.RefreshTokenLifeTime)
            };

            context.Ticket.Properties.IssuedUtc = token.IssuedUtc;

            context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc;

            token.ProtectedTicket = context.SerializeTicket();

            await refreshTokenService.CreateAsync(token);

            context.SetToken(refreshTokenId);
        }
Exemple #2
0
        public UserRepository(OppJarContext context) : base(context)
        {
            UserRoles = context.UserRoles;

            Roles = context.Roles;

            _passwordHasher = ResolverFactory.GetService <IPasswordHasher <User> >();
        }
Exemple #3
0
        protected override bool IsValid(PropertyValidatorContext context)
        {
            var    kioskService = ResolverFactory.GetService <IKioskService>();
            string kioskName    = context.PropertyValue as string;

            var kioskDto = AsyncHelper.RunSync(() => kioskService.FindAllAsync(k => k.Name.ToLower().Equals(kioskName.ToLower())));

            return(kioskDto == null);
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {
                context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

                PulseUserManager userManager = context.OwinContext.GetUserManager <PulseUserManager>();

                PulseIdentityUser user = await userManager.FindAsync(context.UserName, context.Password);

                var userProfileService = ResolverFactory.GetService <IUserProfileService>();

                if (user == null)
                {
                    context.Rejected();

                    context.SetError("Invalid username or password.");

                    return;
                }

                var userProfile = await userProfileService.FindByUserIdAsync(user.Id);

                var authClaimIdentity = await userManager.CreateIdentityAsync(user, OAuthDefaults.AuthenticationType);

                await SaveClaimsAsync(authClaimIdentity, user, userManager);

                var client = context.OwinContext.Get <Client>("oauth:client");

                var roles = await userManager.GetRolesAsync(user.Id);

                var properties = new UserProperties
                {
                    UserName     = authClaimIdentity.Name,
                    ClientId     = user.ClientId,
                    FullName     = userProfile == null ? string.Empty : (string.IsNullOrEmpty(userProfile.FullName.Trim()) ? userProfile.Email : userProfile.FullName),
                    ClientName   = client.Name,
                    Role         = roles.FirstOrDefault(),
                    AvatarPath   = userProfile == null ? string.Empty : (userProfile.AvatarPath == null ? string.Empty : userProfile.AvatarPath),
                    EmailConfirm = user.EmailConfirmed
                };

                var ticket = new AuthenticationTicket(authClaimIdentity,
                                                      CreateProperties(properties)
                                                      );

                context.Validated(ticket);
            }
            catch (Exception ex)
            {
                context.SetError("GrantResourceOwnerCredentials " + ex.Message);

                return;
            }
        }
 private void ProcessServer(HubCallerContext context)
 {
     if (ProcessParameter(context) && !IS_START_COLLECT_DATA_SERVER)
     {
         Process process = ResolverFactory.GetService <Process>();
         process._context       = context;
         process.OnHandleTimer += SendPerfStatusUpdateToClient;
         process.Start();
         IS_START_COLLECT_DATA_SERVER = true;
     }
 }
Exemple #6
0
        public static void Main(string[] args)
        {
            AutoMapperConfiguration.Config();
            NinjectConfiguration.Config();
#if DEBUG
            Process process = ResolverFactory.GetService <Process>();
            process.Start();
            Console.ReadKey();
#else
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[] { new SelfHostService() };
            ServiceBase.Run(ServicesToRun);
#endif
        }
Exemple #7
0
        protected override bool IsValid(PropertyValidatorContext context)
        {
            if (context.Instance.GetValue <int>("Id") == 0)
            {
                var    groupService = ResolverFactory.GetService <IGroupService>();
                string groupName    = context.PropertyValue as string;

                var groupDto = AsyncHelper.RunSync(() => groupService.FindNameAsync(groupName));

                return(groupDto == null);
            }

            return(true);
        }
            protected override bool IsValid(PropertyValidatorContext context)
            {
                var clientService = ResolverFactory.GetService <IClientService>();

                if (context.Instance.GetValue <int>("Id") == 0)
                {
                    string clientName = context.PropertyValue as string;

                    var clientDto = AsyncHelper.RunSync(() => clientService.FindByNameAsync(clientName));

                    return(clientDto == null);
                }

                return(true);
            }
Exemple #9
0
        private async Task <ClaimsIdentity> GetIdentity(string username, string password)
        {
            var userManager = ResolverFactory.GetService <WebApiUserManager>();

            var user = await userManager.FindAsync(username, password);

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

            var authClaimIdentity = await userManager.CreateIdentityAsync(user, OAuthType.AuthenticationType);

            return(authClaimIdentity);
        }
Exemple #10
0
        private async void btn_active_Click(object sender, EventArgs e)
        {
            string licenseKey = txt_license_key.Text;

            if (!string.IsNullOrEmpty(licenseKey))
            {
                panel_liscense.Enabled = false;
                var apiService = ResolverFactory.GetService <KioskApiService>();
                var result     = await apiService.CheckLicenseKeyAsync(licenseKey);

                UpdateKioskSecurity(result);
            }
            else
            {
                MessageBox.Show("Please input license key.");
            }
        }
Exemple #11
0
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            IRefreshTokenService refreshTokenService = ResolverFactory.GetService <RefreshTokenService>();

            string refreshTokenId = UnitHelper.GetHash(context.Token);

            var refreshToken = await refreshTokenService.FindAllRefreshTokensAsync(refreshTokenId);

            if (refreshToken != null)
            {
                context.DeserializeTicket(refreshToken.ProtectedTicket);

                await refreshTokenService.DeleteAsync(refreshToken.Id);
            }
        }
Exemple #12
0
        protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, RolePermissionRequirment requirement)
        {
            var userService = ResolverFactory.GetService <IUserService>();
            var roles       = await userService.GetRolesAsync(context.User.Identity.Name);

            await Task.Run(() =>
            {
                var hasClaim = _roles.Any(s => roles.Contains(s));
                if (!hasClaim)
                {
                    context.Fail();
                    throw new BadRequestException("You are not authorized on this function.");
                }
                else
                {
                    context.Succeed(requirement);
                }
            });
        }
Exemple #13
0
        public override async Task <ClaimsIdentity> CreateIdentityAsync(PulseIdentityUser user, string authenticationType)
        {
            IList <Claim> claims = new List <Claim>();

            PulseUserManager userManager = ResolverFactory.GetService <PulseUserManager>();

            IClientService clientService = ResolverFactory.GetService <IClientService>();

            var roleName = userManager.GetRoles(user.Id).FirstOrDefault();

            var client = await clientService.FindByClientIdAsync(user.ClientId);

            claims.Add(new Claim(ClaimTypes.NameIdentifier, user.Id, null, ClaimsIdentity.DefaultIssuer, "Provider"));
            claims.Add(new Claim(ClaimTypes.Name, user.UserName, null, ClaimsIdentity.DefaultIssuer, "Provider"));
            claims.Add(new Claim("ClientId", user.ClientId, null, ClaimsIdentity.DefaultIssuer, "Provider"));
            claims.Add(new Claim("AllowedGrant", Enum.GetName(typeof(OAuthGrant), client.AllowedGrant), null, ClaimsIdentity.DefaultIssuer, "Provider"));
            claims.Add(new Claim(ClaimTypes.Role, roleName, null, ClaimsIdentity.DefaultIssuer, "Provider"));

            var claimsIdentity = new ClaimsIdentity(claims, authenticationType);

            return(await Task.FromResult(claimsIdentity));
        }
Exemple #14
0
        protected override void OnStart(string[] args)
        {
            try
            {
                _log.Debug("Begin OnStart");
                if (KioskConfigurationHepler.GetValueFromSecurity("LicenseKey") == null && KioskConfigurationHepler.GetValueFromSecurity("LicenseKey") == "")
                {
                    _log.Error("Can't start service with LicenseKey is empty please input LicenseKey before start service thanks");
                    throw new Exception("Can't start service with LicenseKey is empty please input LicenseKey before start service thanks");
                }

                _log.Debug("OnStart Client");
                _process = ResolverFactory.GetService <Process>();
                _process.Start();
                _log.Debug("OnStarted");
            }
            catch (Exception ex)
            {
                _log.Error(ex);
                OnStop();
            }
        }
        private async Task <bool> BeforeAuthorizeAsync(AuthorizationHandlerContext context, TRequirement requirement)
        {
            var curentRole = context.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Role);

            var userId = context.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);

            if (curentRole != null && userId != null)
            {
                var _userManager = ResolverFactory.GetService <UserManager <ApplicationUser> >();

                var user = await _userManager.FindByIdAsync(userId.Value);

                var result = await _userManager.GetRolesAsync(user);

                var dbRole = result.FirstOrDefault();

                if (curentRole.Value != dbRole)
                {
                    return(false);
                }
            }

            return(true);
        }
Exemple #16
0
 private void InitRepository()
 {
     UserRepository = new GenericDataRepository <User>(_transaction, ResolverFactory.GetService <ISqlGenerator <User> >());
 }
 public ServiceBase()
     : this(ResolverFactory.GetService <IRepository <T> >())
 {
 }
        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            try
            {
                string clientId;
                string clientSecret;

                if (context.TryGetBasicCredentials(out clientId, out clientSecret))
                {
                    PulseUserManager userManager = context.OwinContext.GetUserManager <PulseUserManager>();

                    IUnitOfWork unitOfWork = ResolverFactory.GetService <IUnitOfWork>();

                    try
                    {
                        var client = await unitOfWork.Clients.FindAll(c => c.ClientId.Equals(clientId)).FirstOrDefaultAsync();

                        if (client != null &&
                            userManager.PasswordHasher.VerifyHashedPassword(
                                client.Secret, clientSecret) == PasswordVerificationResult.Success)
                        {
                            context.OwinContext.Set("oauth:client", client);

                            string userName = context.Parameters.GetValues("username")[0];

                            var user = await userManager.FindByClientIdAndNameAsync(client.ClientId, userName);

                            if (userManager.IsInRole(user.Id, PulseIdentityRole.Kiosk))
                            {
                                context.Options.AccessTokenExpireTimeSpan = TimeSpan.FromDays(365);
                            }
                            else
                            {
                                context.Options.AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(client.TokenLifeTime);
                            }

                            context.Validated(clientId);
                        }
                        else
                        {
                            context.SetError("invalid_client", "Client credent``ials are invalid.");
                            context.Rejected();
                        }
                    }
                    catch
                    {
                        context.SetError("server_error");
                        context.Rejected();
                    }
                }
                else
                {
                    context.SetError(
                        "invalid_client",
                        "Client credentials could not be retrieved through the Authorization header.");

                    context.Rejected();
                }
            }
            catch (Exception ex)
            {
                context.SetError("ValidateClientAuthentication " + ex.Message);
            }
        }
Exemple #19
0
        public PulseUserManager(IUserStore <PulseIdentityUser> store) : base(store)
        {
            EmailService = ResolverFactory.GetService <IIdentityMessageService>();

            //this.SmsService = new SmsService();
        }
Exemple #20
0
 static DataFactory()
 {
     _configuration = ResolverFactory.GetService <IConfiguration>();
 }