Exemplo n.º 1
0
        public static async Task AttemptLogin(Player player, string user, string pass)
        {
            vPlayer p = (vPlayer)player;
            int     id;
            string  username;
            string  passhash = "";

            var results = await database.Query("SELECT * FROM users WHERE username = '******'");

            id       = results[0]["id"];
            username = results[0]["username"];
            passhash = results[0]["password"];
            bool correct = await Bcrypt.Verify(pass, passhash);

            if (correct)
            {
                p.accountID = id;
                p.loadPlayerData(results[0]["money"], results[0]["skin"], results[0]["bank"], results[0]["staff_level"], results[0]["dim"], results[0]["int"], results[0]["x"], results[0]["y"], results[0]["z"], results[0]["rot"], results[0]["job"]);
                ChatBox.WriteLine("Welcome " + user, player, Slipe.Shared.Utilities.Color.Green);
            }
            else
            {
                ChatBox.WriteLine("Wrong login info.", player, Slipe.Shared.Utilities.Color.Red);
                Slipe.MtaDefinitions.MtaServer.KickPlayer(player.MTAElement, "Xoa", "Invalid login info");
            }
        }
Exemplo n.º 2
0
        public UserControllerTests()
        {
            _connection = new SqliteConnection("Data Source=:memory:");

            _connection.Open();

            var options = new DbContextOptionsBuilder <MobicloneContext>().UseSqlite(_connection).Options;

            _context = new MobicloneContext(options);

            var hash = new Bcrypt();

            var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.Test.json").Build();

            _accessor = new HttpContextAccessor
            {
                HttpContext = new DefaultHttpContext()
            };

            var auth = new Jwt(_context, hash, configuration, _accessor);

            _controller = new UserController(_context, auth, hash);

            _context.Database.EnsureCreated();
        }
Exemplo n.º 3
0
        public async Task <IActionResult> CreateUser([FromBody] Users user)
        {
            try
            {
                if (user == null)
                {
                    _logger.LogError("User object sent from client is null");
                    return(BadRequest("User object is null"));
                }

                if (!ModelState.IsValid)
                {
                    _logger.LogError("Invalid user object sent from client");
                    return(BadRequest("Invalid model object"));
                }
                Bcrypt hash = new Bcrypt(_repository);
                user.Password = hash.Crypting(user.Password);
                await _repository.Users.CreateUsersAsync(user);

                _repository.Save();

                // return 201 status
                return(CreatedAtRoute("CreateUser", new { id = user.Id }, user));
            }
            catch (Exception e)
            {
                _logger.LogError($"Something went wrong inside CreateUsers action: {e.Message}");
                return(StatusCode(500, "Internal server error"));
            }
        }
Exemplo n.º 4
0
        public IHttpActionResult forgotpas([FromBody] _Mail mail)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            Users user = db.users.Where(u => u.email == mail.email).FirstOrDefault();

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

            //generate password reset token
            Random rnd   = new Random();
            string token = Bcrypt.hash(user.email + DateTime.Now.Hour + DateTime.Now.Millisecond + rnd.Next(999999, 999999));

            try
            {
                user.forgot_last_date = DateTime.Now;
                user.password_token   = token;
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                ExceptionThrow.Throw(ex);
            }

            Mailgun.Send("forgot_password", new Dictionary <string, object>()
            {
                { "fullname", user.name + " " + user.lastname }, { "token", token }
            }, user.email, "Menkule Şifre Yenileme Talebiniz");

            return(Ok());
        }
Exemplo n.º 5
0
        public IHttpActionResult changepas([FromBody] _UserPassword password)
        {
            if (password.password != password.reply)
            {
                return(BadRequest());
            }

            int    user_id = Users.GetUserId(User);
            string pas     = Bcrypt.hash(password.currentpassword);

            Users user = db.users.Where(u => u.id == user_id && u.password == pas).FirstOrDefault();

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

            user.password = Bcrypt.hash(password.password);
            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                ExceptionThrow.Throw(ex);
            }
            return(Ok());
        }
Exemplo n.º 6
0
        public async Task <ActionResult> AjouterUtilisateur([FromBody] UtilisateurDTO utilisateurDTO)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //TEST UNIQUE EMAIL ET UNIQUE USERNAME
            Utilisateur utilisateurEmail = await utilisateurDAO.GetUtilisateurByMail(utilisateurDTO.Mail);

            Utilisateur utilisateurUsername = await utilisateurDAO.GetUtilisateurByUsername(utilisateurDTO.Username);

            if (utilisateurEmail != null || utilisateurUsername != null)
            {
                return(BadRequest());
            }

            utilisateurDTO.MotDePasse     = Bcrypt.HashPassword(utilisateurDTO.MotDePasse);
            utilisateurDTO.MotDePasseConf = Bcrypt.HashPassword(utilisateurDTO.MotDePasseConf);
            Utilisateur utilisateur = mapper.Map <Utilisateur>(utilisateurDTO);

            utilisateur = await utilisateurDAO.AjouterUtilisateur(utilisateur);

            return(Created($"api/Utilisateur/{utilisateur.Id}", mapper.Map <UtilisateurDTO>(utilisateur)));
        }
Exemplo n.º 7
0
 public LoginController(IConfiguration config, IRepositoryWrapper repository, ILoggerManager logger)
 {
     _config     = config;
     _repository = repository;
     _logger     = logger;
     JWT         = new JWToken(config);
     hash        = new Bcrypt(repository);
 }
Exemplo n.º 8
0
        public static async Task Register(Player player, string user, string pass)
        {
            var results = await database.Query("SELECT id FROM users WHERE username = ?", user);

            if (results.Length < 1)
            {
                string password = await Bcrypt.Hash(pass);

                database.Exec("INSERT INTO `users` (`username`, `password`) VALUES (?, ?)", user, password);
                var results2 = await database.Query("SELECT id FROM users WHERE username = ?", user);
                await AttemptPlayerRelog(player, results2[0]["id"]);
            }
            else
            {
                ChatBox.WriteLine("That username has been taken.", player, Slipe.Shared.Utilities.Color.Red);
            }
        }
Exemplo n.º 9
0
        public ExpenseControllerTests()
        {
            var builder = new DbContextOptionsBuilder <MobicloneContext>().UseInMemoryDatabase("expense");

            _context = new MobicloneContext(builder.Options);

            var hash = new Bcrypt();

            var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.Test.json").Build();

            _accessor = new HttpContextAccessor
            {
                HttpContext = new DefaultHttpContext()
            };

            var auth = new Jwt(_context, hash, configuration, _accessor);

            _controller = new ExpenseController(_context, auth);
        }
Exemplo n.º 10
0
        public IHttpActionResult resetpas([FromBody] _TokenResetPassword _token)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (_token.password != _token.reply)
            {
                return(BadRequest());
            }

            Users user = db.users.Where(u => u.password_token == _token.token).FirstOrDefault();

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

            if (user.forgot_last_date != null)
            {
                TimeSpan diff = DateTime.Now - Convert.ToDateTime(user.forgot_last_date);
                if (diff.TotalHours >= 2)
                {
                    return(BadRequest());
                }
            }

            try
            {
                user.password         = Bcrypt.hash(_token.password);
                user.forgot_last_date = null;
                user.password_token   = null;
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                ExceptionThrow.Throw(ex);
            }

            return(Ok());
        }
Exemplo n.º 11
0
        private async void HandleLogin(Player source, LoginRpc rpc)
        {
            var result = await database.Query("SELECT * FROM `users` WHERE username = ?", rpc.Username);

            if (result.Length == 0)
            {
                RpcManager.Instance.TriggerRPC(source, "Login.Error", new ErrorRpc("These credentials do not match our records."));
                return;
            }
            var userData = result[0];

            string passwordHash = userData["password"];

            if (!await Bcrypt.Verify(rpc.Password, passwordHash))
            {
                RpcManager.Instance.TriggerRPC(source, "Login.Error", new ErrorRpc("These credentials do not match our records."));
                return;
            }

            RpcManager.Instance.TriggerRPC(source, "Login.Success", new EmptyRpc());
        }
Exemplo n.º 12
0
        public IHttpActionResult externalConfirm([FromBody] _ExternalConfirm externalConfirmData)
        {
            int user_id = Users.GetUserId(User);

            if (externalConfirmData.password != externalConfirmData.reply)
            {
                ExceptionThrow.Throw("Şifre tekrarı hatalı.", HttpStatusCode.BadRequest);
            }

            if (db.users.Any(u => u.gsm == externalConfirmData.gsm))
            {
                ExceptionThrow.Throw("gsm no kullanılmaktadır.", HttpStatusCode.BadRequest);
            }

            Users user = db.users.Where(u => u.id == user_id && u.is_external_confirm == false).FirstOrDefault();

            if (user == null)
            {
                ExceptionThrow.Throw("Zaten şifre güncellenmiş", HttpStatusCode.Forbidden);
            }

            user.gsm                 = externalConfirmData.gsm;
            user.updated_date        = DateTime.Now;
            user.password            = Bcrypt.hash(externalConfirmData.password);
            user.is_external_confirm = true;

            try
            {
                db.SaveChanges();

                //Send Gsm Activation Code
                NetGsm.Send(externalConfirmData.gsm, "menkule.com.tr uyeliginiz ile ilgili onay kodunuz: " + user.gsm_activation_code);
            }
            catch (Exception ex)
            {
                ExceptionThrow.Throw(ex);
            }
            return(Ok());
        }
        // OAuthAuthorizationServerProvider sınıfının kaynak erişimine izin verebilmek için ilgili GrantResourceOwnerCredentials metotunu override ediyoruz.
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            // Kullanıcının access_token alabilmesi için gerekli validation işlemlerini yapıyoruz.
            string pass = Bcrypt.hash(context.Password);
            Users  usr  = db.users.Where(u => u.email == context.UserName && u.password == pass).FirstOrDefault();

            if (usr == null)
            {
                context.SetError("invalid_grant", "Kullanıcı adı veya şifre yanlış.");
                return;
            }
            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim("user_id", usr.id.ToString()));

            //Role eklemek için
            if (usr.ownershiping)
            {
                identity.AddClaim(new Claim(ClaimTypes.Role, "owner"));
            }
            context.Validated(identity);
        }
Exemplo n.º 14
0
        private async void HandleRegister(Player source, RegisterRpc rpc)
        {
            if (rpc.Password != rpc.PasswordConfirmation)
            {
                RpcManager.Instance.TriggerRPC(source, "Register.Error", new ErrorRpc("These passwords are not the same."));
                return;
            }

            if (string.IsNullOrEmpty(rpc.Username) || string.IsNullOrEmpty(rpc.Password) || string.IsNullOrEmpty(rpc.Email))
            {
                RpcManager.Instance.TriggerRPC(source, "Register.Error", new ErrorRpc("Please fill in the entire form."));
                return;
            }

            if (!(rpc.Email.Contains("@") && rpc.Email.Contains(".")))
            {
                RpcManager.Instance.TriggerRPC(source, "Register.Error", new ErrorRpc("Please fill in a valid email."));
                return;
            }

            if ((await database.Query("SELECT id FROM `users` WHERE email = ?", rpc.Email)).Length > 0)
            {
                RpcManager.Instance.TriggerRPC(source, "Register.Error", new ErrorRpc("This email address is already in use."));
                return;
            }

            if ((await database.Query("SELECT id FROM `users` WHERE username = ?", rpc.Username)).Length > 0)
            {
                RpcManager.Instance.TriggerRPC(source, "Register.Error", new ErrorRpc("This username address is already in use."));
                return;
            }

            string hash = await Bcrypt.Hash(rpc.Password);

            database.Exec("INSERT INTO `users` (`username`, `email`, `password`) VALUES (?, ?, ?)", rpc.Username, rpc.Email, hash);

            RpcManager.Instance.TriggerRPC(source, "Register.Success", new EmptyRpc());
        }
Exemplo n.º 15
0
        public async Task <IActionResult> Login([FromBody] LoginModelDTO loginModelDTO)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var repository = new AuthenticationRepository(this.context);
            //Utilisateur userFound = repository.GetUtilisateurs().FirstOrDefault(u => u.Username == loginModelDTO.Username && u.MotDePasse == loginModelDTO.Password);
            Utilisateur userFound = repository.GetUtilisateurs().FirstOrDefault(u => u.Username == loginModelDTO.Username && Bcrypt.Verify(loginModelDTO.Password, u.MotDePasse));

            if (userFound == null)
            {
                return(Unauthorized());
            }

            var claims = new List <Claim> {
                new Claim(JwtRegisteredClaimNames.Sub, userFound.Username),
                new Claim(JwtRegisteredClaimNames.Jti, await _jwtOptions.JtiGenerator()),
                new Claim(JwtRegisteredClaimNames.Iat,
                          ToUnixEpochDate(_jwtOptions.IssuedAt).ToString(),
                          ClaimValueTypes.Integer64),
                new Claim(PrivateClaims.UserId, userFound.Id.ToString())
            };

            //ADD role
            if (userFound.UtilisateurRole != null)
            {
                userFound.UtilisateurRole.ToList().ForEach(u => claims.Add(new Claim("roles", u.IdRoleNavigation.Nom)));
            }

            JwtSecurityToken token = new JwtSecurityToken(
                issuer: _jwtOptions.Issuer,
                audience: _jwtOptions.Audience,
                claims: claims,
                notBefore: _jwtOptions.NotBefore,
                expires: _jwtOptions.Expiration,
                signingCredentials: _jwtOptions.SigningCredentials
                );
            var encodedJwt = new JwtSecurityTokenHandler().WriteToken(token);

            var response = new{
                access_token = encodedJwt,
                expires_in   = (int)_jwtOptions.ValidFor.TotalSeconds,
            };

            return(Ok(response));
        }
Exemplo n.º 16
0
 public SubjectsController(ILoggerManager logger, IRepositoryWrapper repository)
 {
     _logger     = logger;
     _repository = repository;
     hash        = new Bcrypt(_repository);
 }
Exemplo n.º 17
0
        /// <summary>
        /// Read private key parameters with OpenSSH format.
        /// </summary>
        /// <param name="passphrase">passphrase for decrypt the key file</param>
        /// <param name="keyPair">key pair</param>
        /// <param name="comment">comment or empty if it didn't exist</param>
        public void Load(string passphrase, out KeyPair keyPair, out string comment)
        {
            // Note:
            //  The structure of the private key format is described in "PROTOCOL.key" file in OpenSSH sources.

            String base64Text;

            using (StreamReader sreader = GetStreamReader()) {
                string line = sreader.ReadLine();
                if (line == null)
                {
                    throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unexpected eof)");
                }

                if (line != PrivateKeyFileHeader.SSH2_OPENSSH_HEADER_OPENSSH)
                {
                    throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unexpected key type)");
                }

                string footer = line.Replace("BEGIN", "END");

                StringBuilder buf = new StringBuilder();
                while (true)
                {
                    line = sreader.ReadLine();
                    if (line == null)
                    {
                        throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unexpected eof)");
                    }
                    if (line == footer)
                    {
                        break;
                    }
                    buf.Append(line);
                }
                base64Text = buf.ToString();
            }

            byte[] blob = Base64.Decode(Encoding.ASCII.GetBytes(base64Text));

            int numKeys;    // number of keys

            byte[][] publicKeyBlobs;
            byte[]   privateKeyData;
            bool     decrypted;

            using (var blobStream = new MemoryStream(blob, false)) {
                if (!CheckMagic(blobStream))
                {
                    throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unsupported format)");
                }

                string          cipherName = ReadString(blobStream);
                CipherAlgorithm?cipherAlgorithm;
                int             cipherKeySize;
                int             cipherIVSize;
                switch (cipherName)
                {
                case "none":
                    cipherAlgorithm = null;
                    cipherKeySize   = 0;
                    cipherIVSize    = 0;
                    break;

                case "aes128-cbc":
                    cipherAlgorithm = CipherAlgorithm.AES128;
                    cipherKeySize   = 16;
                    cipherIVSize    = 16;   // use block size
                    break;

                case "aes192-cbc":
                    cipherAlgorithm = CipherAlgorithm.AES192;
                    cipherKeySize   = 24;
                    cipherIVSize    = 16;   // use block size
                    break;

                case "aes256-cbc":
                    cipherAlgorithm = CipherAlgorithm.AES256;
                    cipherKeySize   = 32;
                    cipherIVSize    = 16;   // use block size
                    break;

                default:
                    throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unsupported cipher)");
                }

                string kdfName = ReadString(blobStream);
                if (kdfName != "bcrypt" && kdfName != "none")
                {
                    throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (unsupported kdf)");
                }

                if ((cipherName == "none") != (kdfName == "none"))
                {
                    throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid cipher)");
                }

                byte[] kdfOptions = ReadBytes(blobStream);
                if (kdfOptions == null)
                {
                    throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (missing kdf options)");
                }
                byte[] kdfSalt;
                uint   kdfRounds;
                byte[] key;
                byte[] iv;
                if (kdfName == "none")
                {
                    kdfSalt   = null;
                    kdfRounds = 0;
                    key       = null;
                    iv        = null;
                }
                else
                {
                    if (!ReadKdfOptions(kdfOptions, out kdfSalt, out kdfRounds))
                    {
                        throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid kdf options)");
                    }

                    if (passphrase == null || passphrase.Length == 0)
                    {
                        throw new SSHException(Strings.GetString("WrongPassphrase"));
                    }

                    // prepare decryption
                    Bcrypt bcrypt = new Bcrypt();
                    byte[] tmpkey = bcrypt.BcryptPbkdf(passphrase, kdfSalt, kdfRounds, cipherKeySize + cipherIVSize);
                    if (tmpkey == null)
                    {
                        throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid kdf options)");
                    }
                    key = new byte[cipherKeySize];
                    Buffer.BlockCopy(tmpkey, 0, key, 0, cipherKeySize);
                    iv = new byte[cipherIVSize];
                    Buffer.BlockCopy(tmpkey, cipherKeySize, iv, 0, cipherIVSize);
                }

                if (!ReadInt32(blobStream, out numKeys) || numKeys < 0)
                {
                    throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (missing keys)");
                }

                publicKeyBlobs = new byte[numKeys][];
                for (int i = 0; i < numKeys; ++i)
                {
                    byte[] data = ReadBytes(blobStream);
                    if (data == null)
                    {
                        throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (missing public keys)");
                    }
                    publicKeyBlobs[i] = data;
                }

                privateKeyData = ReadBytes(blobStream);
                if (privateKeyData == null)
                {
                    throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (missing private keys)");
                }

                if (cipherAlgorithm.HasValue && key != null && iv != null)
                {
                    // decrypt private keys
                    Cipher cipher = CipherFactory.CreateCipher(SSHProtocol.SSH2, cipherAlgorithm.Value, key, iv);
                    cipher.Decrypt(privateKeyData, 0, privateKeyData.Length, privateKeyData, 0);
                    decrypted = true;
                }
                else
                {
                    decrypted = false;
                }
            }

            using (var privateKeysStream = new MemoryStream(privateKeyData, false)) {
                uint check1, check2;
                if (!ReadUInt32(privateKeysStream, out check1) ||
                    !ReadUInt32(privateKeysStream, out check2))
                {
                    throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (invalid private keys)");
                }
                if (check1 != check2)
                {
                    throw new SSHException(decrypted ?
                                           Strings.GetString("WrongPassphrase") : Strings.GetString("NotValidPrivateKeyFile"));
                }

                for (int i = 0; i < numKeys; ++i)
                {
                    string privateKeyType = ReadString(privateKeysStream);

                    using (var publicKeyBlobStream = new MemoryStream(publicKeyBlobs[i], false)) {
                        string publicKeyType = ReadString(publicKeyBlobStream);
                        if (publicKeyType != privateKeyType)
                        {
                            throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (key type unmatched)");
                        }

                        switch (privateKeyType)
                        {
                        case "ssh-ed25519": {
                            byte[] pk = ReadBytes(privateKeysStream);
                            if (pk == null)
                            {
                                throw new SSHException(Strings.GetString("NotValidPrivateKeyFile"));
                            }
                            byte[] sk = ReadBytes(privateKeysStream);
                            if (sk == null)
                            {
                                throw new SSHException(Strings.GetString("NotValidPrivateKeyFile"));
                            }
                            string cmnt = ReadString(privateKeysStream);           // comment
                            if (cmnt == null)
                            {
                                throw new SSHException(Strings.GetString("NotValidPrivateKeyFile"));
                            }

                            byte[] publicKey = ReadBytes(publicKeyBlobStream);
                            if (publicKey == null)
                            {
                                throw new SSHException(Strings.GetString("NotValidPrivateKeyFile"));
                            }

                            // sanity check
                            if (!AreEqual(publicKey, pk))
                            {
                                throw new SSHException(Strings.GetString("WrongPassphrase"));
                            }

                            // first 32 bytes of secret key is used as a private key for ed25519
                            byte[] privateKey = new byte[32];
                            if (sk.Length < privateKey.Length)
                            {
                                throw new SSHException(Strings.GetString("NotValidPrivateKeyFile"));
                            }
                            Buffer.BlockCopy(sk, 0, privateKey, 0, privateKey.Length);

                            var curve = EdwardsCurve.FindByAlgorithm(PublicKeyAlgorithm.ED25519);
                            if (curve != null)
                            {
                                var kp = new EDDSAKeyPair(curve, new EDDSAPublicKey(curve, publicKey), privateKey);
                                if (!kp.CheckKeyConsistency())
                                {
                                    throw new SSHException(Strings.GetString("NotValidPrivateKeyFile"));
                                }
                                keyPair = kp;
                                comment = cmnt;
                                return;
                            }
                        }
                        break;

                        default:
                            // unsupported key type; check the next key.
                            break;
                        }
                    }
                }
            }

            throw new SSHException(Strings.GetString("NotValidPrivateKeyFile") + " (supported private key was not found)");
        }
Exemplo n.º 18
0
        public IHttpActionResult add([FromBody] Users user)
        {
            //validation
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            if (db.users.Any(u => u.email == user.email))
            {
                ExceptionThrow.Throw("e-posta adresi kullanılmaktadır.", HttpStatusCode.BadRequest);
            }
            if (db.users.Any(u => u.gsm == user.gsm))
            {
                ExceptionThrow.Throw("gsm no kullanılmaktadır.", HttpStatusCode.BadRequest);
            }

            //generate activation code
            Random rnd        = new Random();
            string gsm_code   = rnd.Next(9999, 999999).ToString();
            string email_code = rnd.Next(9999, 999999).ToString();

            //set password
            bool   no_password = user.password == null || user.password.Trim() == "";
            string password    = no_password ? Users.generatePassword(5, 3) : user.password;

            //create user
            Users userData = new Users
            {
                name                  = user.name,
                lastname              = user.lastname,
                email                 = user.email,
                gender                = user.gender,
                gsm                   = user.gsm,
                description           = user.description,
                password              = Bcrypt.hash(password),
                source                = "web",
                email_activation_code = email_code,
                gsm_activation_code   = gsm_code
            };


            if (user.identity_no != null)
            {
                userData.identity_no = user.identity_no;
            }

            //insert user
            db.users.Add(userData);

            try
            {
                db.SaveChanges();

                //If password is random generated
                if (no_password)
                {
                    NetGsm.Send(user.gsm, "Menkule.com.tr üyelik şifreniz " + password + " Şifrenizi değiştirmeyi unutmayınız.");
                }
            }
            catch (Exception ex)
            {
                ExceptionThrow.Throw(ex);
            }

            //Send Gsm Activation Code
            NetGsm.Send(user.gsm, "menkule.com.tr uyeliginiz ile ilgili onay kodunuz: " + gsm_code);

            //Send Email Notification
            Mailgun.Send("register", new Dictionary <string, object>()
            {
                { "fullname", user.name + " " + user.lastname }
            }, user.email, "Üyeliğiniz için teşekkürler");

            object token = no_password ? Users.LoginOnBackDoor(user.email, password) : null;


            return(Ok(new
            {
                name = user.name,
                lastname = user.lastname,
                email = user.email,
                gsm = user.gsm,
                gender = user.gender,
                photo = "",
                ownershiping = user.ownershiping,
                state = user.state,
                email_state = user.email_state,
                gsm_state = user.gsm_state,
                created_date = user.created_date,
                token = token
            }));
        }
        public async Task <IHttpActionResult> facebookLogin(string provider, string error = null)
        {
            string redirectUri = string.Empty;
            Dictionary <string, string> AccessToken = null;

            // Validate request
            if (error != null)
            {
                return(BadRequest(Uri.EscapeDataString(error)));
            }

            // Exist Identity
            if (!User.Identity.IsAuthenticated)
            {
                return(new ChallengeResult(provider, this));
            }

            // Validate redirect url
            var redirectUriValidationResult = ValidateClientAndRedirectUri(Request, ref redirectUri);

            if (!string.IsNullOrWhiteSpace(redirectUriValidationResult))
            {
                return(BadRequest(redirectUriValidationResult));
            }

            // User data from Identity
            UserFacebook externalLogin = UserFacebook.FromIdentity(User.Identity as ClaimsIdentity);

            if (externalLogin == null)
            {
                return(InternalServerError());
            }

            // Exist user in db
            Users user          = db.users.Where(u => (u.facebook_id == externalLogin.ProviderKey && u.email == externalLogin.Email && u.source == "facebook")).FirstOrDefault();
            bool  hasRegistered = user != null;

            // If not identity register to db add new user
            if (!hasRegistered)
            {
                try
                {
                    // check user e-mail exist validation
                    if (db.users.Any(u => u.email == externalLogin.Email))
                    {
                        return(Redirect(GenerateErrorRedirect(externalLogin, "e-posta zaten kullanilmakta", redirectUri)));
                    }

                    string password = Users.generatePassword(5, 3);

                    //generate activation code
                    Random rnd        = new Random();
                    string gsm_code   = rnd.Next(9999, 999999).ToString();
                    string email_code = rnd.Next(9999, 999999).ToString();

                    // disable db validations
                    db.Configuration.ValidateOnSaveEnabled = false;

                    // create user
                    Users userData = new Users
                    {
                        name                  = externalLogin.FirstName,
                        lastname              = externalLogin.LastName,
                        email                 = externalLogin.Email,
                        facebook_id           = externalLogin.ProviderKey,
                        gender                = externalLogin.Gender == "male" ? "Bay" : "Bayan",
                        gsm                   = string.Empty,
                        password              = Bcrypt.hash(password),
                        source                = "facebook",
                        email_activation_code = email_code,
                        gsm_activation_code   = gsm_code,
                        is_external_confirm   = false,
                    };
                    db.users.Add(userData);

                    // save photos
                    byte[] imageData = null;
                    using (var wc = new System.Net.WebClient())
                        imageData = wc.DownloadData(externalLogin.Photo.Data.Url);
                    MemoryStream photoStreamData = new MemoryStream(imageData);

                    // send cloud
                    var    image       = new WebImage(photoStreamData);
                    var    httpRequest = HttpContext.Current.Request;
                    Images userImage   = Cloudinary.upload(image, "users/" + userData.name.ReduceWhitespace().Replace(" ", "-").ToEng() + "-" + userData.lastname.ReduceWhitespace().Replace(" ", "-").ToEng() + "-" + userData.id);
                    if (userImage != null)
                    {
                        db.images.Add(userImage);
                        db.SaveChanges();
                        userData.image_id = userImage.id;
                    }

                    db.SaveChanges();

                    // enable db validations
                    db.Configuration.ValidateOnSaveEnabled = false;

                    return(Redirect(GenerateRedirectUrl(AuthBackdoor.auth(userData, Request), externalLogin, hasRegistered, redirectUri)));
                }
                catch (Exception ex)
                {
                    return(Redirect(GenerateErrorRedirect(externalLogin, ex.Message.ToString(), redirectUri)));
                }
            }
            return(Redirect(GenerateRedirectUrl(AuthBackdoor.auth(user, Request), externalLogin, hasRegistered, redirectUri)));
        }
Exemplo n.º 20
0
 public ReservationsController(ILoggerManager logger, IRepositoryWrapper repository)
 {
     _logger     = logger;
     _repository = repository;
     hash        = new Bcrypt(_repository);
 }