public StatisticsService(authDbContext context,
                          IAuthUser authUser, ILogger <StatisticsService> logger)
 {
     _context  = context;
     _authUser = authUser;
     _logger   = logger;
 }
        public User GetUserByNameAndPassword(IAuthUser user)
        {
            SqlParameter usernameParameter = new SqlParameter("@UserName", user.UserName);
            SqlParameter passwordParameter = new SqlParameter("@Password", user.Password);

            return(_context.Users.FromSql($"SELECT * FROM dbo.Users WHERE UserName = @UserName AND Password = @Password", usernameParameter, passwordParameter).FirstOrDefault());
        }
 public HospitalManagementService(authDbContext context,
                                  ILogger <HospitalManagementService> logger, IAuthUser authUser)
 {
     _context  = context;
     _logger   = logger;
     _authUser = authUser;
 }
        public (string token, int userId) GenerateToken(IAuthUser authUser)
        {
            User user = _userRepository.GetUserByNameAndPassword(authUser);

            if (user == null)
            {
                _userRepository.Insert(_userBuilder.WithUserName(authUser.UserName)
                                       .WithPassword(authUser.Password)
                                       .WithRole(authUser.Role)
                                       .Build());
            }

            JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler();

            byte[] key = Encoding.ASCII.GetBytes(_appSettings.Secret);

            SecurityTokenDescriptor tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.UserName),
                    new Claim(ClaimTypes.Role, authUser.Role ?? string.Empty)
                }),
                Expires            = DateTime.UtcNow.AddYears(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return(tokenHandler.WriteToken(token), user.Id);
        }
示例#5
0
        public virtual async Task <bool> DeviceExist(T model, IAuthUser <int, TRole, T> user)
        {
            try
            {
                var device = _cache?.FindFirst(m => m.DeviceId == model.DeviceId && m.UserId == user.Id);
                if (device != null)
                {
                    return(true);
                }
                device = await _db.FirstOrDefaultAsync(m => m.DeviceId == model.DeviceId && m.UserId == user.Id);

                if (device != null)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (Exception ext)
            {
                throw new Exception(ext.Message, ext);
            }
        }
        public async Task <IActionResult> Login(string email, string password)
        {
            IAuthUser user = null;

            //TODO check if null

            try
            {
                user = await Auth.Authenticate(email, password);
            }
            catch (UnauthorizedAccessException ex)
            {
                return(Json(new
                {
                    success = false,
                    error = ex.Message
                }));
            }

            Response.CreateAuthCookie(user.ID, "DBID");

            return(Json(new
            {
                success = true,
                redirect = "/"
            }));
        }
示例#7
0
 public LocationManagementService(authDbContext context,
                                  ILogger <LocationManagementService> logger, IAuthUser authUser)
 {
     _context  = context;
     _logger   = logger;
     _authUser = authUser;
 }
示例#8
0
        /// <summary>登录或注册完成后,保存登录信息</summary>
        /// <param name="user"></param>
        protected virtual void SaveLogin(IAuthUser user)
        {
            var u = user as IMyModel;

            u.Type    = Type;
            u.Version = Version;
            if (u.NickName.IsNullOrEmpty())
            {
                u.NickName = "{0}{1}".F(Agent, user.Name);
            }

            var dic = ControllerContext.Current?.Parameters?.ToNullable();

            if (dic != null)
            {
                NetType = dic["NetType"] + "";

                var olt = Online as IMyOnline;
                olt.LoginTime = DateTime.Now;
                olt.LoginCount++;
                // 本地地址
                olt.InternalUri = dic["ip"] + "";
                olt.NetType     = NetType;
            }

            var ns = Session as NetSession;

            user.SaveLogin(ns);
        }
        /// <summary>
        /// Assigns the user and ID and saves it to the "database"
        /// </summary>
        /// <param name="u"></param>
        /// <returns></returns>
        public async Task <IAuthUser> CreateAccount(IAuthUser u)
        {
            AuthUser user = (AuthUser)u;

            if (SQL.SQLStatements.ValidateTenantEmail(user.Email.ToLower()) == true)
            {
                throw new CreateAccountException("A user with this email address already exists!");
            }

            //if (FakeDBCredStore.Any(c => c.Email.ToLower() == user.Email.ToLower()))
            //{
            //    throw new CreateAccountException("A user with this email address already exists!");
            //}
            //user.ID = StringHelper.RandomString(32);

            var tenant = new Tenant()
            {
                EmailAddress = user.Email,
                PasswordHash = user.PasswordHash,
                Role         = user.Role,
            };

            SQL.SQLStatements.AddTenant(tenant);
            //FakeDBCredStore.Add(user);

            return(user);
        }
示例#10
0
 static DependencyResolver()
 {
     _settingsDao   = new Settings();
     _settingsLogic = new SettingsLogic(_settingsDao);
     if (ConfigurationManager.AppSettings["DAL"].Equals("Memory"))
     {
         _userDao  = new Memory();
         _awardDao = new MemoryAward();
     }
     else
     {
         if (ConfigurationManager.AppSettings["DAL"].Equals("TextFile"))
         {
             _userDao  = new TextFiles(SettingsLogic);
             _awardDao = new TextFileAward(SettingsLogic);
             SettingsLogic.SetPath(ConfigurationManager.AppSettings["PathToFile"]);
             SettingsLogic.SetPathToUsers(ConfigurationManager.AppSettings["PathToAuthFile"]);
             SettingsLogic.SetPathToImages(ConfigurationManager.AppSettings["PathToImages"]);
         }
     }
     _authUserDao   = new AuthUserTextFile(_settingsLogic);
     _authUserLogic = new AuthUserLogic(_authUserDao);
     _userLogic     = new UserLogic(_userDao);
     _awardLogic    = new AwardLogic(_awardDao);
 }
示例#11
0
 public SMSManagmentService(IConfiguration config, IServiceScopeFactory serviceScope, ILogger <SMSManagmentService> logger,
                            IAuthUser authuser)
 {
     _config       = config;
     _serviceScope = serviceScope;
     _logger       = logger;
     _authuser     = authuser;
 }
示例#12
0
 /// <summary>
 /// 上线
 /// </summary>
 /// <param name="key">用户认证标识</param>
 /// <param name="user"></param>
 /// <param name="ns"></param>
 public static void AddAuth(string key, IAuthUser user, string ns = "http://www.bi7prk.com/")
 {
     if (dict.ContainsKey(key))
     {
         dict.Remove(key); //挤下线
     }
     dict.Add(key, user);
     _NS = ns;
 }
示例#13
0
 public PaymentService(authDbContext context, IConfiguration config, ILogger <PaymentService> logger,
                       IAuthUser authUser, StatisticsService statisticsService)
 {
     _context           = context;
     _config            = config;
     _logger            = logger;
     _authUser          = authUser;
     _statisticsService = statisticsService;
 }
示例#14
0
        public static void HashPassword(this IAuthUser user)
        {
            if (user.Password == null)
            {
                return;
            }

            user.PasswordHash = PasswordHash.CreateHash(user.Password);
            user.Password     = null;
        }
示例#15
0
 public LogHandler(
     ISysOprationLogService oprationLogService,
     IAuthUser authUser,
     IHttpContextAccessor accessor
     )
 {
     _oprationLogService = oprationLogService;
     _authUser           = authUser;
     _accessor           = accessor;
 }
示例#16
0
 protected internal virtual ActivityEntity UpdateEntity(IAuthUser dealer)
 {
     this.Entity.Variables  = this.Variables.ToString();
     this.Entity.Outputs    = this.Outputs.ToString();
     this.Entity.Status     = this.Status;
     this.Entity.DealedBy   = dealer.UserId;
     this.Entity.DealerInfo = dealer.UserInfo;
     this.Entity.DealTime   = DateTime.Now;
     return(this.Entity);
 }
示例#17
0
        /// <summary>比较密码MD5</summary>
        /// <param name="user"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        public static Boolean CheckMD5(this IAuthUser user, String pass)
        {
            // 验证密码
            if (user.Password != pass.MD5())
            {
                throw new Exception(user + " 密码错误");
            }

            return(true);
        }
        public IAuthUserDTO Login(IAuthUser authUser)
        {
            if (ValidateUser(authUser))
            {
                var(token, userId) = GenerateToken(authUser);
                return(AuthUserDTO.Create(userId, token));
            }

            throw new UnauthorizedAccessException("Usuário ou senha incorretos");
        }
示例#19
0
 public MessageManagementService(authDbContext context, IDataProtectionProvider dataProtectionProvider,
                                 IAuthUser authUser, ILogger <MessageManagementService> logger,
                                 IServiceScopeFactory serviceScope)
 {
     _context      = context;
     _protector    = dataProtectionProvider.CreateProtector(GetType().FullName);
     _authUser     = authUser;
     _logger       = logger;
     _serviceScope = serviceScope;
 }
示例#20
0
        /// <summary>
        /// 上线
        /// </summary>
        /// <param name="user">默认标识键为 UserId</param>
        /// <param name="ns"></param>
        public static void AddAuth(IAuthUser user, string ns = "http://www.bi7prk.com/")
        {
            var strKey = user.UserId.ToString();

            if (dict.ContainsKey(strKey))
            {
                dict.Remove(strKey); //挤下线
            }
            dict.Add(strKey, user);
            _NS = ns;
        }
        public bool ValidateUser(IAuthUser authUser)
        {
            User user = _userRepository.GetUserByNameAndPassword(authUser);

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

            return(false);
        }
 public AccountManagementService(RoleManager <BtRole> roleManager, UserManager <BtUser> userManager,
                                 ILogger <AccountManagementService> logger, authDbContext context, IAuthUser authUser,
                                 IHttpContextAccessor accessor, IDataProtectionProvider dataProtectionProvider)
 {
     _roleManager = roleManager;
     _userManager = userManager;
     _context     = context;
     _authUser    = authUser;
     _logger      = logger;
     _protector   = dataProtectionProvider.CreateProtector(GetType().FullName);
     _accessor    = accessor;
 }
 public SysGroupService(
     IMapper mapper,
     ICache cache,
     IAuthUser authUser,
     ISysGroupRepository sysGroupRepository
     )
 {
     _mapper             = mapper;
     _cache              = cache;
     _authUser           = authUser;
     _sysGroupRepository = sysGroupRepository;
 }
示例#24
0
 /// <summary>
 /// 构造函数 参数对象系统自动注入
 /// </summary>
 /// <param name="mapper">autoMapper 映射工具对象</param>
 /// <param name="cache">缓存对象</param>
 /// <param name="authUser">授权用户对象</param>
 /// <param name="sysConditionRepository">仓储对象</param>
 public SysConditionService(
     IMapper mapper,
     ICache cache,
     IAuthUser authUser,
     ISysConditionRepository sysConditionRepository
     )
 {
     _mapper   = mapper;
     _cache    = cache;
     _authUser = authUser;
     _sysConditionRepository = sysConditionRepository;
 }
示例#25
0
 /// <summary>
 /// 构造函数 参数对象系统自动注入
 /// </summary>
 /// <param name="mapper">autoMapper 映射工具对象</param>
 /// <param name="cache">缓存对象</param>
 /// <param name="authUser">授权用户对象</param>
 /// <param name="dictionaryEntryRepository">仓储对象</param>
 public DictionaryEntryService(
     IMapper mapper,
     ICache cache,
     IAuthUser authUser,
     IDictionaryEntryRepository dictionaryEntryRepository
     )
 {
     _mapper   = mapper;
     _cache    = cache;
     _authUser = authUser;
     _dictionaryEntryRepository = dictionaryEntryRepository;
 }
示例#26
0
 public SysOprationLogService(
     IAuthUser user,
     IMapper mapper,
     IHttpContextAccessor accessor,
     ISysOprationLogRepository oprationLogRepository
     )
 {
     _user     = user;
     _mapper   = mapper;
     _accessor = accessor;
     _oprationLogRepository = oprationLogRepository;
 }
示例#27
0
 public SysTaskQzService(
     IMapper mapper,
     ICache cache,
     ISysTaskQzRepository SysTaskQzRepository,
     IAuthUser authUser,
     ISchedulerCenter schedulerCenter
     )
 {
     _mapper = mapper;
     _cache  = cache;
     _SysTaskQzRepository = SysTaskQzRepository;
     _authUser            = authUser;
     _schedulerCenter     = schedulerCenter;
 }
        public void InsertAuthUser(IAuthUser _authuser)
        {
            var p = new
            {
                firstname = _authuser.FirstName,
                lastname  = _authuser.LastName,
                gender    = _authuser.Gender,
                role      = _authuser.Role,
                email     = _authuser.EmailAddress,
                password  = _authuser.Password
            };

            _helper.SaveData <dynamic>(INSERT_PROCEDURE_NAME, p);
        }
示例#29
0
        async Task <Queue <Activity> > InitTodoListAsync(IAuthUser dealer)
        {
            var dealingActivityEntities = await this.ActivityRepository.ListDealingByFlowIdAndDealerIdAsync(this.Id, dealer.UserId);

            var todos = new Queue <Activity>();

            foreach (var entity in dealingActivityEntities)
            {
                var activity = this.ActivityFactory.Create(entity, this, dealer);
                todos.Enqueue(activity);
            }

            return(todos);
        }
示例#30
0
 public SysApiService(
     IAuthUser authUser,
     ICache cache,
     IMapper mapper,
     ISysApiRepository sysApiRepository,
     IApiDomain apiDomain
     )
 {
     _authUser         = authUser;
     _cache            = cache;
     _mapper           = mapper;
     _sysApiRepository = sysApiRepository;
     _apiDomain        = apiDomain;
 }
示例#31
0
        /// <summary>
        /// This method retrieves the correct user object from the CDS for the specific domain.
        /// </summary>
        /// <param name="context">The request context.</param>
        /// <param name="username">The username containing the userid and the domain.</param>
        /// <param name="rqUser">An out parameter that contains the user obejct if the request is successful.</param>
        /// <returns>Returns the HTTP status code for the request. 200 indicated success, everything else indicates a fail.</returns>
        protected virtual string RetrieveUserSecurity(SiteControllerContext context, MailAddress username, out IAuthUser rqUser)
        {
            Content secEnt = null;
            try
            {
                Type userType = context.ContextSettings.ResolveSecurityObjectType(username.Host);

                throw new NotImplementedException();
                string status;;// = context.CDSHelper.Execute(userType, CDSData.Get(CDSAction.Read, "userid", username.Address), out secEnt);

                rqUser = secEnt as IAuthUser;

                return status;
            }
            catch (Exception ex)
            {
                //OK, we have an error. Tidy up any mess and returns any objects to the pool.
                if (secEnt != null && secEnt.ObjectPoolCanReturn)
                    secEnt.ObjectPoolReturn();

                rqUser = null;
                return CH.HTTPCodes.InternalServerError_500;
            }
        }
 /// <summary>
 /// effectively (re)sends a user an email with their activation details
 /// </summary>
 /// <param name="au"></param>
 /// <param name="ou"></param>
 /// <param name="password"></param>
 public virtual void EmailActivation(IAuthUser au, IUser ou, string password)
 {
     Email.EmailActivation(ou,au,OrgStore,password );
     
 }
示例#33
0
        public bool AuthenticationSet(IAuthUser rqUser, bool persist, bool? authenticated)
        {
            string userID = rqUser.UserName;
            string userRealm = rqUser.RealmDomain;

            bool response =
                AuthenticationSet(userRealm, userID, persist, authenticated);


            return response;
        }
示例#34
0
 private static void CreatePasswordResetNotification(string password,IDocumentStore orgStore,IAuthUser authUser)
 {
     using (var session = orgStore.OpenSession())
     {
         var user =session.Load<User>(authUser.Id);
         Email.PasswordReset(user, orgStore, password);
     }
 }
示例#35
0
        /// <summary>
        /// This method sets the session value
        /// </summary>
        /// <param name="context">The current context.</param>
        /// <param name="rqMember">The member account to set.</param>
        /// <returns>Returns </returns>
        protected virtual bool SessionSet(SiteControllerContext context, IAuthUser rqUser)
        {
            if (context.ScriptSession == null || rqUser == null)
                return false;

            return context.ScriptSession.AuthenticationSet(rqUser, false, true);
        }
示例#36
0
        public static void EmailActivation(IUser ou, IAuthUser au, IDocumentStore store,string password)
        {
            var activationurl = String.Format("{0}://{1}/{2}", "https", ConfigurationManager.AppSettings["ActivationUrl"], au.ActivationCode);

            var body = GetActivationEmailBody(ou, activationurl, au.ActivationCode,password);
            var notification = new Notification
            {
                About = ou.ToSimpleUser(),
                Body = body,
                Id = IlluminateDatabase.GenerateId<Notification>(),
                SendDate = DateTime.Now,
                Title = "Illuminate Account Activation Code",
                NotificationRecipients = new[]
                                                                    {
                                                                        new NotificationRecipient
                                                                            {
                                                                                NotificationDeliveryTypes =
                                                                                    NotificationDeliveryTypes.Email,
                                                                                Users = new[]
                                                                                            {
                                                                                                ou.ToSimpleUser()
                                                                                            }
                                                                            }
                                                                    }
            };

            using (var session = store.OpenSession())
            {
                session.Store(notification);
                session.SaveChanges();
            }
        }