Пример #1
0
 /// <summary>
 /// Funzione per l'inizializzazione del manager dei token di autenticazione
 /// </summary>
 private void InitializeSecurityToken()
 {
     if (_authTokenManager == null)
     {
         _authTokenManager = AuthTokenManager.GetInstance(ConfigurationManager.AppSettings["AuthManagerFullName"]);
     }
 }
Пример #2
0
        public OpenIDLoginResponse(OpenIDResponseType responseType, string id, string issuer, string audience, IdentityModel identity, string x509Thumbprint, string nonce, string state)
        {
            if (responseType == OpenIDResponseType.Code)
            {
                this.AccessCode = AuthTokenManager.GenerateAccessCode(id, identity);
            }
            else if (responseType == OpenIDResponseType.IdToken)
            {
                this.ID       = id;
                this.Issuer   = issuer;
                this.Subject  = Guid.NewGuid().ToString();
                this.Audience = audience;
                this.UserID   = identity.UserID;
                this.UserName = identity.UserName;
                this.Roles    = identity.Roles;

                this.KeyID          = x509Thumbprint;
                this.X509Thumbprint = x509Thumbprint; //same https://docs.microsoft.com/en-us/azure/active-directory/develop/id-tokens
                this.Nonce          = nonce;
                this.State          = state;

                this.IssuedAtTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
                this.NotBefore    = DateTimeOffset.UtcNow.AddMinutes(-5).ToUnixTimeSeconds();
                this.Expiration   = DateTimeOffset.UtcNow.AddMinutes(5).ToUnixTimeSeconds();
            }
            else
            {
                throw new IdentityProviderException($"Not supported response type {responseType}");
            }
        }
Пример #3
0
        public static void GetUserPin()
        {
            if (mArgs.Count != 2)
            {
                Log("Usage: GetUserPin <useremail>");
                return;
            }

            //if (!long.TryParse(mArgs[1], out long idUser)) throw new ArgumentException("userid");

            using (var c = new PostgresqlDataLayer(mDbConfig).GetConn())
            {
                var dbUser = c.QueryFirstOrDefault <User>("SELECT * FROM users WHERE email ilike @email", new { email = mArgs[1] });
                if (dbUser == null)
                {
                    throw new Exception("Email not found");
                }

                var user = new User
                {
                    Id    = dbUser.Id,
                    Email = mArgs[1]
                };

                var tokenManager = new AuthTokenManager(new TokenAuthConfig());

                var pin = UsersController.GetActivationPin(tokenManager, user);
                Log($"Pin: {pin}");
            }
        }
Пример #4
0
 public UsersController(
     AuthTokenManager tokenManager,
     NotificationManager notificationManager,
     IOptions <Config> config) : base(config)
 {
     mTokenManager = tokenManager;
     mNotifier     = notificationManager;
 }
Пример #5
0
        // Consider password transformation (if available in plain text, we can import it).

        public static ImportResult Import(IDbConnection c, string inputFile, long idCreator)
        {
            var result = new ImportResult();

            // TODO:
            // - remove this, support upload.
            // - support the case of empty fields. So far, height and weight cannot be empty, check with other numbers as well.
            inputFile = @"C:\users\dsuar\Desktop\user sample data.csv";

            using (var r = File.OpenText(inputFile))
            {
                var csv = new CsvReader(r, new Configuration {
                    //HeaderValidated = (isValid, headerNames, headerNameIndex, context) => { },
                    HeaderValidated          = null,
                    MissingFieldFound        = null,
                    ReadingExceptionOccurred = (ex) =>
                    {
                        result.Errors.Add(new ImportError
                        {
                            Line       = ex.ReadingContext.RawRecord,
                            Error      = ex.Message,
                            LineNumber = ex.ReadingContext.RawRow,
                            Column     = ex.ReadingContext.CurrentIndex
                        });
                        result.NumRecordsWithError++;
                    }
                });

                var records = csv.GetRecords <Player>();

                var t = c.BeginTransaction();

                try
                {
                    foreach (var player in records)
                    {
                        var p = player.UserData.Password;

                        HashedPassword hashPass = (p != null) ? AuthTokenManager.HashPassword(p) : null;

                        // TODO: validate email / mobile doesn't exist already

                        PlayersController.InsertPlayer(c, t, player, player.UserData.Id, idCreator, true, hashPass, UserEventType.PlayerImported);
                    }

                    t.Commit();
                }
                catch
                {
                    t.Rollback();
                }
            }

            return(result);
        }
Пример #6
0
        public OpenIDTokenResponse(string code)
        {
            var token = AuthTokenManager.GetToken(nameof(OpenIDTokenResponse), code);

            if (token == null)
            {
                throw new IdentityProviderException("Invalid access code");
            }

            this.Token = token;
        }
Пример #7
0
        public OAuth2TokenResponse(string serviceProvider, string code)
        {
            var token = AuthTokenManager.GetToken(serviceProvider, code);

            if (token == null)
            {
                throw new IdentityProviderException("Invalid access code");
            }

            this.ServiceProvider = serviceProvider;
            this.Token           = token;
        }
        public void PinGenerator()
        {
            var user = new User {
                Id = 19, Email = "*****@*****.**"
            };

            var tm = new AuthTokenManager(new TokenAuthConfig());

            var pin1 = UsersController.GetActivationPin(tm, user);
            var pin2 = UsersController.GetActivationPin(tm, user);

            Assert.AreEqual(pin1, pin2);
        }
Пример #9
0
        private static void HashPasswordInUser(User user)
        {
            if (user == null || user.Password == null || user.Password == "")
            {
                return;
            }

            // Take the clearTextPassword in the password field and hash it

            var hashedPass = AuthTokenManager.HashPassword(user.Password);

            user.Password = hashedPass.Hash;
            user.Salt     = hashedPass.Salt;
        }
Пример #10
0
        public OAuth2IdentityResponse(string serviceProvider, string token)
        {
            var identity = AuthTokenManager.GetIdentity(serviceProvider, token);

            if (identity == null)
            {
                throw new IdentityProviderException("Invalid token");
            }

            this.ServiceProvider = serviceProvider;
            this.UserID          = identity.UserID;
            this.UserName        = identity.UserName;
            this.Roles           = identity.Roles;
        }
Пример #11
0
        public void NegativePin()
        {
            // 114  [email protected]

            var user = new User
            {
                Id    = 114,
                Email = "*****@*****.**"
            };

            var authManager = new AuthTokenManager(new TokenAuthConfig());

            var pin = UsersController.GetActivationPin(authManager, user);

            Assert.AreEqual("0214", pin);
        }
Пример #12
0
        public static string GetActivationPin(AuthTokenManager tm, User user)
        {
            var token = tm.CreateActivationToken(user.Id, user.Email);
            int hash  = (byte)token[token.Length - 2] << 8 + (byte)token[token.Length - 1];

            if (hash < 0)
            {
                hash = -hash;
            }
            var pin = hash.ToString("0000").Substring(0, 4);

            if (pin.StartsWith('-'))
            {
                pin = '0' + pin.Substring(1);
            }

            return(pin);
        }
Пример #13
0
        public void Init()
        {
            _signInManager         = new Mock <ISignInManager>();
            _userManager           = new Mock <IUserManager>();
            _refreshTokenManager   = new Mock <IRefreshTokenManager>();
            _tokenHelper           = new Mock <ITokenHelper>();
            _orgHelper             = new Mock <IOrgHelper>();
            _appInstanceManager    = new Mock <IAppInstanceManager>();
            _authRequestValidators = new Mock <IAuthRequestValidators>();

            var tokenOptions = new TokenAuthOptions()
            {
                AccessExpiration  = TimeSpan.FromMinutes(90),
                RefreshExpiration = TimeSpan.FromDays(90),
            };

            _authTokenManager = new AuthTokenManager(new Mock <IAppInstanceRepo>().Object, _refreshTokenManager.Object, _authRequestValidators.Object, _orgHelper.Object, _tokenHelper.Object, _appInstanceManager.Object, new Mock <IAdminLogger>().Object, _signInManager.Object, _userManager.Object);

            _appInstanceManager.Setup(ais => ais.UpdateLastLoginAsync(It.IsAny <string>(), It.IsAny <AuthRequest>())).ReturnsAsync(InvokeResult <AppInstance> .Create(new AppInstance("rowid", "userid")));
            _appInstanceManager.Setup(ais => ais.UpdateLastAccessTokenRefreshAsync(It.IsAny <string>(), It.IsAny <AuthRequest>())).ReturnsAsync(InvokeResult <AppInstance> .Create(new AppInstance("rowid", "userid")));

            _signInManager.Setup(sim => sim.PasswordSignInAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>(), It.IsAny <bool>())).Returns(Task.FromResult(InvokeResult.Success));
            _userManager.Setup(usm => usm.FindByIdAsync(It.IsAny <string>())).Returns(Task.FromResult(new AppUser()
            {
                Id = Guid.NewGuid().ToId()
            }));
            _userManager.Setup(usm => usm.FindByNameAsync(It.IsAny <string>())).Returns(Task.FromResult(new AppUser()
            {
                Id = Guid.NewGuid().ToId()
            }));
            _orgHelper.Setup(ohlp => ohlp.SetUserOrgAsync(It.IsAny <AuthRequest>(), It.IsAny <AppUser>())).Returns(Task.FromResult(InvokeResult.Success));
            _refreshTokenManager.Setup(rtm => rtm.GenerateRefreshTokenAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns(Task <RefreshToken> .FromResult(InvokeResult <RefreshToken> .Create(new RefreshToken("XXXX"))));
            _authRequestValidators.Setup(arv => arv.ValidateAuthRequest(It.IsAny <AuthRequest>())).Returns(InvokeResult.Success);
            _authRequestValidators.Setup(arv => arv.ValidateAccessTokenGrant(It.IsAny <AuthRequest>())).Returns(InvokeResult.Success);
            _authRequestValidators.Setup(arv => arv.ValidateRefreshTokenGrant(It.IsAny <AuthRequest>())).Returns(InvokeResult.Success);
            _tokenHelper.Setup(tlp => tlp.GenerateAuthResponse(It.IsAny <AppUser>(), It.IsAny <AuthRequest>(), It.IsAny <InvokeResult <RefreshToken> >())).Returns(new InvokeResult <AuthResponse>()
            {
                Result = new AuthResponse()
                {
                    AccessToken           = "ACC",
                    AccessTokenExpiresUTC = DateTime.Now.AddMinutes(30).ToJSONString(),
                }
            });
        }
Пример #14
0
        private User ValidateUser(IDbConnection c, InputLoginInfo loginInfo)
        {
            var user = GetUserForEmail(c, loginInfo.Email);

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

            // the email matches, now check password
            var salt           = Convert.FromBase64String(user.Salt);
            var hashedPassword = AuthTokenManager.HashPassword(loginInfo.Password, salt);

            if (!hashedPassword.Equals(user.Password))
            {
                return(null);
            }

            return(user);

            // May require email confirmation to allow login.
        }
 public RefereesController(NotificationManager notifier, IOptions <Config> config, AuthTokenManager authManager) : base(config)
 {
     mNotifier         = notifier;
     mAuthTokenManager = authManager;
 }
Пример #16
0
 public EnrollmentController(IOptions <Config> config, NotificationManager notif, AuthTokenManager authManager) : base(config)
 {
     mNotifications    = notif;
     mAuthTokenManager = authManager;
 }
Пример #17
0
 public OAuth2LoginResponse(string serviceProvider, IdentityModel identity, string state)
 {
     this.ServiceProvider = serviceProvider;
     this.AccessCode      = AuthTokenManager.GenerateAccessCode(serviceProvider, identity);
     this.State           = state;
 }