Example #1
0
 public AuthService(IRepository repository, IMapper mapper, IHashing hashing, IOptions <AuthOptions> authOptions)
 {
     this.repository  = repository;
     this.mapper      = mapper;
     this.hashing     = hashing;
     this.authOptions = authOptions;
 }
Example #2
0
 public UserLogic(IUserDAO userDAO, ISQLDAO dao, ILoggerIO log, IHashing hasher)
 {
     hash     = hasher;
     logs     = log;
     userData = userDAO;          //injecting dependency
     userData.GetDataWriter(dao); //dependency injector through a infrastructure
 }
Example #3
0
 public AccountService(CocktailDatabaseContext dbContext, IHashing hasher, IBarService barService, ICocktailService cService)
 {
     this.hasher     = hasher;
     this.barService = barService;
     this.cService   = cService;
     this.dbContext  = dbContext;
 }
Example #4
0
 public PrevRateLogic(IPrevRateDAO PrevRateDAO, ISQLDAO dao, ILoggerIO log, IHashing hasher)
 {
     hash         = hasher;
     logs         = log;
     PrevRateData = PrevRateDAO;      //injecting dependency
     PrevRateData.GetDataWriter(dao); //dependency injector through a infrastructure
 }
        public UsersModule(IUsers users, IPasswordGenerator passwordGenerator,
            IHashing hashing, IEmailGateway emailGateway, IEventLog eventLog)
            : base("/User")
        {
            this.users = users;
            this.passwordGenerator = passwordGenerator;
            this.hashing = hashing;
            this.emailGateway = emailGateway;
            this.eventLog = eventLog;

            Post["/"] = x =>
                            {
                                var email = Request.Query.email.ToString();

                                if (!string.IsNullOrEmpty(email))
                                {
                                    var fromDb = this.users.Get(email);
                                    if (fromDb != null)
                                        return Response.AsJson(new[] {fromDb});

                                    var password = this.users.Create(email);
                                    return Response.AsJson(new[] {new {password}});
                                }
                                return Response.AsJson(Enumerable.Empty<string>());
                            };

            Get["/PasswordReset"] = x =>
                                        {
                                            return View["passwordreset", new Result  { Success = false }];
                                        };

            Post["/PasswordReset"] = x =>
                                         {
                                             bool result = false;
                                             var input = this.Bind<PasswordResetBody>();
                                             if(!string.IsNullOrWhiteSpace(input.email))
                                             {
                                                 var user = this.users.Get(input.email);
                                                 if(user!= null)
                                                 {
                                                     var password = this.passwordGenerator.Generate();
                                                     var hashedPassword = this.hashing.Hash(password);
                                                     this.users.ChangePassword(user.Id, hashedPassword);
                                                     this.emailGateway.SendNewPasswordEmail(user.Email, password);
                                                     result = true;

                                                     this.eventLog.LogEvent(new Event()
                                                                                {
                                                                                    AuthorId = user.Id,
                                                                                    BarCodeId = null,
                                                                                    EventName = "CHANGEPASSWORD",
                                                                                    Ip = this.Request.Headers["X-Forwarded-For"].FirstOrDefault()
                                                                                });
                                                 }
                                             }

                                             return View["passwordreset", new Result { Success = result }];
                                         };
        }
        public static T GetDigest <T>(this IHashing <T> hashing, string text, Encoding encoding)
        {
            hashing.Init();
            var data = encoding.GetBytes(text);

            hashing.Write(data, 0, (uint)data.Length);
            return(hashing.GetDigest());
        }
        /// <summary>
        /// Instantiates the Playercontroller with a repo of choice. Use memory repository for unit testing
        /// </summary>
        /// <param name="emailSender">The email service to use</param>
        /// <param name="databaseManager">The database manager to use</param>
        /// <param name="hashing">The hashing service to use</param>
//        public PlayerController(IPlayerRepository repo)
//        {
//            repository = repo;
//        }
//This SHOULD work but, Asp.net core offers dependency injection etc. I feel this may cause bugs!!
        public PlayerController(IEmailSender emailSender, IDatabaseManager databaseManager, IHashing hashing)
        {
            _emailSender = emailSender;
            _hashing     = hashing;
            //  _protector = provider.CreateProtector("PlayerController"); OK, the protector gives different values no matter what I do. New plan.
            _repository   = new PlayerRepository(new PlayerSQLContext(databaseManager));
            _loginManager = new LoginManager(new PlayerRepository(new PlayerSQLContext(databaseManager)));
        }
Example #8
0
 public TenantCreateCommandHandler(
     IMapper mapper,
     IUnitOfWork <ITenantDbContext> unitOfWork,
     ITenantRepository tenantRepository,
     IHashing hashing
     ) : base(tenantRepository, mapper, unitOfWork)
 {
     _hashing = hashing;
 }
Example #9
0
 public ConnectionStringsSettings(IHashing hashing) :
     base("ConnectionStrings")
 {
     if (hashing == null)
     {
         throw new ArgumentNullException("hashing");
     }
     _hashing = hashing;
 }
Example #10
0
 public bool ChangePassword(string oldPassword, string newPassword, IHashing textHashing)
 {
     if (PasswordIsValid(oldPassword, textHashing))
     {
         SetPassword(newPassword, textHashing);
         return true;
     }
     return false;
 }
Example #11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ShardService"/> class.
        /// </summary>
        /// <param name="nodeRepository">Concrete Node repository</param>
        /// <param name="hashingFunction">Concrete Hashsing function</param>
        /// <param name="vNodes">Number of virtual nodes - default = 10</param>
        public ShardService(INodeRepository nodeRepository, IHashing hashingFunction, int vNodes = 10)
        {
            this.nodeRepository = nodeRepository;
            var nodes = nodeRepository.GetAllNode();

            if (nodes == null || nodes.Count == 0) throw new Exception("No available node, check your connection string or database");

            ClusterManager = new ClusterManager(nodes, hashingFunction, vNodes);
        }
 /// <summary>
 /// Initializes an object of the hash table class.
 /// </summary>
 public HashTable(IHashing hashing)
 {
     this.hashing = hashing;
     count        = 0;
     bucket       = new List <int> [100];
     for (int i = 0; i < 100; ++i)
     {
         bucket[i] = new List <int>();
     }
 }
 public static void Write <T>(this IHashing <T> hashing, params int[] values)
 {
     for (int i = 0; i < values.Length; i++)
     {
         var v = values[i];
         hashing.WriteByte((byte)(v >> 0));
         hashing.WriteByte((byte)(v >> 8));
         hashing.WriteByte((byte)(v >> 16));
         hashing.WriteByte((byte)(v >> 24));
     }
 }
Example #14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ShardService"/> class.
        /// </summary>
        /// <param name="nodeRepository">Concrete Node repository</param>
        /// <param name="hashingFunction">Concrete Hashsing function</param>
        /// <param name="vNodes">Number of virtual nodes - default = 10</param>
        public ShardService(INodeRepository nodeRepository, IHashing hashingFunction, int vNodes = 10)
        {
            this.nodeRepository = nodeRepository;
            var nodes = nodeRepository.GetAllNode();

            if (nodes == null || nodes.Count == 0)
            {
                throw new Exception("No available node, check your connection string or database");
            }

            ClusterManager = new ClusterManager(nodes, hashingFunction, vNodes);
        }
Example #15
0
 public TenantAuthenticateCommandHandler(
     IMapper mapper,
     ILogger <TenantAuthenticateCommandHandler> logger,
     IConfiguration appSettings,
     ITenantRepository tenantRepository,
     IHashing hashing,
     IJwtTokenFactory jwtTokenFactory
     ) : base(tenantRepository, mapper, logger)
 {
     _appSettings     = appSettings;
     _hashing         = hashing;
     _jwtTokenFactory = jwtTokenFactory;
 }
Example #16
0
        protected async Task LoginOffline()
        {
            // grab the user from local resource
            Dsr = await LoginController.GetByDsrPhoneNumberAsync(Settings.DsrPhone);

            // no local profile present
            if (Dsr == null)
            {
                ShowLoginResultMessage(Resource.String.no_offline_profile);
                this._canLoginOffline = false;
                return;
            }

            // profile exists, continue

            // check whether it has been too long since the user logged in online
            if (!LoginService.LoginValid(Dsr.LastOnlineLogin, DateTime.Today, Settings.ExpirePeriodInDays))
            {
                ShowLoginResultMessage(string.Format(GetString(Resource.String.logging_in_too_long), Settings.ExpirePeriodInDays));
                this._canLoginOffline = false;
                return;
            }

            // check the amount of times logged in offline
            if (Dsr.OfflineLoginAttempts >= Settings.OfflineLoginAttempts)
            {
                ShowLoginResultMessage(string.Format(GetString(Resource.String.logging_in_offline_expire), Dsr.OfflineLoginAttempts));
                this._canLoginOffline = false;
                return;
            }

            // we're still ok, check the hash
            IHashing hashing = Resolver.Instance.Get <IHashing>();
            string   hash    = hashing.HashPassword(Settings.DsrPhone, EnteredPin);

            if (hash != Dsr.PinHash)
            {
                Dsr.OfflineLoginAttempts++;
                await LoginController.SaveAsync(Dsr);

                ShowLoginResultMessage(Resource.String.wrong_pin);
                return;
            }

            // seem to be right PIN, so continue
            Dsr.LastOfflineLogin     = DateTime.Now;
            Dsr.OfflineLoginAttempts = 0;
            await LoginController.SaveAsync(Dsr);

            ContinueToWelcome();
        }
 public MainViewModel()
 {
     OutputChangedCommand   = new RelayCommand(new Action <object>(UpdateOutput));
     ValidMACChangedCommand = new RelayCommand(new Action <object>(Validate));
     // Fills the option with diffent types of hashing
     hashingOptions = new ObservableCollection <HashingType>()
     {
         new HashingType()
         {
             Managed = false, Type = "SHA1", Name = "SHA1"
         },
         new HashingType()
         {
             Managed = false, Type = "SHA256", Name = "SHA256"
         },
         new HashingType()
         {
             Managed = false, Type = "SHA384", Name = "SHA384"
         },
         new HashingType()
         {
             Managed = false, Type = "SHA512", Name = "SHA512"
         },
         new HashingType()
         {
             Managed = false, Type = "MD5", Name = "MD5"
         },
         new HashingType()
         {
             Managed = true, Type = "SHA1", Name = "SHA1 Managed"
         },
         new HashingType()
         {
             Managed = true, Type = "c", Name = "SHA256 Managed"
         },
         new HashingType()
         {
             Managed = true, Type = "SHA384", Name = "SHA384 Managed"
         },
         new HashingType()
         {
             Managed = true, Type = "SHA512", Name = "SHA512 Managed"
         },
     };
     selectedHashing = hashingOptions[0];
     hashing         = new HmacHashing(selectedHashing.Type);
 }
Example #18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ClusterManager"/> class.
        /// </summary>
        /// <param name="nodeRepository">Concrete Node repository</param>
        /// <param name="hashingFunction">Concrete Hashsing function</param>
        /// <param name="vNodes">Number of virtual nodes - default = 10</param>
        public ClusterManager(IEnumerable <Node> nodes, IHashing hashingFunction, int vNodes = 10)
        {
            if (vNodes <= 0)
            {
                throw new Exception("vNodes must greater than 0");
            }
            if (nodes == null || !nodes.Any())
            {
                throw new Exception("No available node");
            }

            this.hashingFunction = hashingFunction;
            this.vNodes          = vNodes;
            this.ring            = new SortedDictionary <int, Node>();
            this.Nodes           = new Dictionary <Guid, Node>();

            foreach (var node in nodes)
            {
                AddNode(node);
            }
            ayKeys = ring.Keys.ToArray();
        }
 /// <summary>
 /// hashes the users input
 /// </summary>
 public void InputChanges(object obj = null)
 {
     // Creates the Hashing object if it is managed or not
     if (selectedHashing.Managed)
     {
         hashing = new Hashing();
     }
     else
     {
         hashing = new HmacHashing();
     }
     // Sets the hashingtype
     hashing.SetHashingType(selectedHashing.Name);
     // Converts the message to bytes using ascii
     byte[] message = Encoding.ASCII.GetBytes(this.message);
     // Hashes the message
     Time   = hashing.ComputeMAC(ref message, Encoding.ASCII.GetBytes(key));
     hashed = message;
     // Updates the output
     UpdateOutput(obj);
     // Validates the generatede mac with the inputed mac
     Validate(obj);
 }
Example #20
0
 private string HashPasswordWithUserSalt(string password, IHashing hashing)
 {
     return hashing.CreateHash(password, GetUserSalt());
 }
Example #21
0
 public void SetPassword(string password, IHashing hashing)
 {
     PasswordHash = HashPasswordWithUserSalt(password, hashing);
     Modified();
 }
Example #22
0
 public bool UserHashIsValid(string userHash, IHashing hashing)
 {
     return userHash == GetWebUserHash(hashing);
 }
Example #23
0
 public string GetWebUserHash(IHashing hashing)
 {
     string identity = string.Format(CultureInfo.InvariantCulture, @"{0}{1}", Id, Username);
     return HashPasswordWithUserSalt(identity, hashing).Substring(0, 8);
 }
Example #24
0
 public bool PasswordIsValid(string password, IHashing hashing)
 {
     return string.Compare(HashPasswordWithUserSalt(password, hashing), PasswordHash) == 0;
 }
        public UsersModule(IUsers users, IPasswordGenerator passwordGenerator,
                           IHashing hashing, IEmailGateway emailGateway, IEventLog eventLog) : base("/User")
        {
            this.users             = users;
            this.passwordGenerator = passwordGenerator;
            this.hashing           = hashing;
            this.emailGateway      = emailGateway;
            this.eventLog          = eventLog;

            Post["/"] = x =>
            {
                var email = Request.Query.email.ToString();

                if (!string.IsNullOrEmpty(email))
                {
                    var fromDb = this.users.Get(email);
                    if (fromDb != null)
                    {
                        return(Response.AsJson(new[] { fromDb }));
                    }

                    var password = this.users.Create(email);
                    return(Response.AsJson(new[] { new { password } }));
                }
                return(Response.AsJson(Enumerable.Empty <string>()));
            };

            Get["/PasswordReset"] = x =>
            {
                return(View["passwordreset", new Result  {
                                Success = false
                            }]);
            };

            Post["/PasswordReset"] = x =>
            {
                bool result = false;
                var  input  = this.Bind <PasswordResetBody>();
                if (!string.IsNullOrWhiteSpace(input.email))
                {
                    var user = this.users.Get(input.email);
                    if (user != null)
                    {
                        var password       = this.passwordGenerator.Generate();
                        var hashedPassword = this.hashing.Hash(password);
                        this.users.ChangePassword(user.Id, hashedPassword);
                        this.emailGateway.SendNewPasswordEmail(user.Email, password);
                        result = true;

                        this.eventLog.LogEvent(new Event()
                        {
                            AuthorId  = user.Id,
                            BarCodeId = null,
                            EventName = "CHANGEPASSWORD",
                            Ip        = this.Request.Headers["X-Forwarded-For"].FirstOrDefault()
                        });
                    }
                }

                return(View["passwordreset", new Result {
                                Success = result
                            }]);
            };
        }
Example #26
0
 public Users(IHashing hashing, IPasswordGenerator passwordGenerator)
 {
     this.hashing = hashing;
     this.passwordGenerator = passwordGenerator;
 }
Example #27
0
 public void SetUp()
 {
     _hashing = ServiceLocator.Current.Get <IHashing>();
 }
 public UserController(IHashing hashing, IDataManager dataManager)
 {
     this.hashing = hashing;
     this.dataManager = dataManager;
     this.hashing = new HmacHashing(Encoding.UTF8.GetBytes("hello world"), "sha512");
 }
Example #29
0
 public UserController(IUserBL userBL, IMapper mapper, IHashing hasher)
 {
     _userBL = userBL;
     _mapper = mapper;
     _hasher = hasher;
 }
Example #30
0
 public ulong GetHash(IHashing <ulong> hashing)
 {
     return(hashing.GetDigest(NameStringOffset, (int)Type));
 }
 public LoginValidation(IHashing hashing)
 {
     this.hashing = hashing;
 }
Example #32
0
 public AuthController(IIdentityService userService, IHashing hashing)
 {
     this.userService = userService;
     this.hashing     = hashing;
 }
Example #33
0
 public LoginManager(IPlayerRepository playerRepository)
 {
     _playerRepo = playerRepository;
     _hashing    = new Hashing();
 }
Example #34
0
 public UserService(IUsersRepository usersRepository, IHashing hashing, ICloudStorage cloudStorage)
 {
     UsersRepository = usersRepository;
     Hashing         = hashing;
     CloudStorage    = cloudStorage;
 }
Example #35
0
        /// <summary>
        /// Attempts to perform an online login
        /// </summary>
        /// <param name="phone">The phone number of the individual logging in</param>
        /// <param name="pin">The associated pin</param>
        /// <param name="isFirstTime">Flag for whether it is the first time the individual is log</param>
        /// <param name="filterFlags">Flags to help ignore some API errors</param>
        /// <returns>Null if login failed or on success a DsrProfile object containing details of user who's logged in</returns>
        public async Task <LoginResponse> Login(string phone, string pin, bool isFirstTime, ErrorFilterFlags filterFlags)
        {
            try
            {
                if (pin == null)
                {
                    return(new LoginResponse {
                        Code = LoginResponseCode.WrongParameters
                    });
                }

                if (phone == null)
                {
                    return(new LoginResponse {
                        Code = LoginResponseCode.WrongParameters
                    });
                }

                IHashing hashing = Resolver.Instance.Get <IHashing>();
                string   hash    = hashing.HashPassword(phone, pin);

                string credentials = string.Format("{0}:{1}", phone, hash);
                byte[] bytes       = hashing.GetBytes(credentials);

                string base64 = Convert.ToBase64String(bytes);

                this.RemoveHeader("Authorization");
                this.AddHeader("Authorization", " Basic " + base64);
                ServerResponse <LoginResponse> response = await PostObjectAsync <LoginResponse, LoginDto>(
                    new LoginDto
                {
                    Hash              = hash,
                    IsFirstLogin      = isFirstTime,
                    DeviceInformation = Resolver.Instance.Get <IInformation>()
                },
                    null,
                    filterFlags);

                this.Logger.Debug("Call to login api completed");

                if (response == null)
                {
                    this.Logger.Debug("Response is null");
                    return(new LoginResponse()
                    {
                        Code = LoginResponseCode.HttpError
                    });
                }

                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    this.Logger.Debug("HttpStatusCode.Unauthorized");
                    return(new LoginResponse()
                    {
                        Code = LoginResponseCode.Unauthorized
                    });
                }

                if (!response.IsSuccessStatus)
                {
                    this.Logger.Debug("IsSuccessStatus = false");
                    return(new LoginResponse()
                    {
                        Code = LoginResponseCode.HttpError
                    });
                }

                this.Logger.Debug("Persisting user hash");
                Resolver.Instance.Get <ISalesAppSession>().UserHash = base64;

                this.Logger.Debug("deserializing response text to object");
                LoginResponse loginResponse = response.GetObject();

                if (loginResponse.Permissions == null || !loginResponse.Permissions.Any())
                {
                    this.Logger.Debug("Looks like we don't yet support permissions. Lets fake some.");
                    var vals = Enum.GetNames(typeof(Permissions));
                    loginResponse.Permissions = new List <Permission>();
                    foreach (string value in vals)
                    {
                        this.Logger.Debug(string.Format("Faking permission: {0}", value));

                        loginResponse.Permissions.Add(
                            new Permission
                        {
                            Name         = value,
                            PermissionId = (uint)Enum.Parse(typeof(Permissions), value)
                        });
                    }
                }

                this.Logger.Debug(string.Format("Updating permissions total permissions count {0}", loginResponse.Permissions.Count));
                await PermissionsController.Instance.UpdatePermissionsAsync(loginResponse.Permissions);

                this.Logger.Debug("Login went smoothly... Exiting method and returning result");
                loginResponse.Code = LoginResponseCode.Success;
                return(loginResponse);
            }
            catch (Exception ex)
            {
                this.Logger.Error(ex);
                return(new LoginResponse()
                {
                    Code = LoginResponseCode.Unknown
                });
            }
        }
 public static T GetDigest <T>(this IHashing <T> hashing, string text)
 {
     return(hashing.GetDigest(text, Encoding.UTF8));
 }
 public bool PasswordIsValid(string password, IHashing hashing)
 {
     return hashing.CreateHash(password, Created) == PasswordHash;
 }
Example #38
0
 public ulong GetHash(IHashing <ulong> hashing)
 {
     return(hashing.GetDigest(AttributeTableIndex, AttributeCount, ElementTableIndex, ElementCount, NameStringOffset, VariantOffset));
 }
Example #39
0
 public ulong GetHash(IHashing <ulong> hashing)
 {
     return(hashing.GetDigest(NameStringOffset, VariantOffset));
 }
 public static T GetDigest <T>(this IHashing <T> hashing, params int[] values)
 {
     hashing.Init();
     hashing.Write(values);
     return(hashing.GetDigest());
 }
Example #41
0
 public Users(IHashing hashing, IPasswordGenerator passwordGenerator)
 {
     this.hashing           = hashing;
     this.passwordGenerator = passwordGenerator;
 }