Beispiel #1
0
        public async Task <IActionResult> GetToken(ApiUsers user)
        {
            var userExist = await _apiUsers.UserDidExist(user);

            if (userExist)
            {
                var secretKey = _config.GetValue <string>("SecretKey");
                var key       = Encoding.ASCII.GetBytes(secretKey);
                var claims    = new[]
                {
                    new Claim(ClaimTypes.NameIdentifier, user.UserName),
                    new Claim(ClaimTypes.Email, user.Email)
                };

                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject            = new ClaimsIdentity(claims),
                    Expires            = DateTime.Now.AddDays(1),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
                                                                SecurityAlgorithms.HmacSha256Signature),
                };

                var tokenHandler = new JwtSecurityTokenHandler();
                var createdToken = tokenHandler.CreateToken(tokenDescriptor);
                return(Ok(tokenHandler.WriteToken(createdToken)));
            }

            return(BadRequest("Your User Does Not exist"));
        }
Beispiel #2
0
        public async Task <IActionResult> PutUsers(int id, ApiUsers users)
        {
            if (id != users.UserId)
            {
                return(BadRequest("User does not exist."));
            }

            var resource = ApiMapper.MapUsers(users);

            try
            {
                await _repo.UpdateUserAsync(resource);
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!await _repo.UserExistAsync(id))
                {
                    return(NotFound("User not found."));
                }
                else
                {
                    throw;
                }
            }

            return(Ok("User updated."));
        }
        public ApiUsers AuthUsers(string EmptorUsername)
        {
            ApiUsers apiUsers = new ApiUsers();

            var Record = RobinDB.RBN_EMPTOR_API_USERS.Where(X => X.Active == true).Where(X => X.EmptorUsername == EmptorUsername).FirstOrDefault();

            if (Record != null)
            {
                apiUsers = new ApiUsers()
                {
                    Success = true,
                    Message = "Kullanıcı sisteme tanımlı, token verilebilir."
                };
            }
            else
            {
                apiUsers = new ApiUsers()
                {
                    Success = false,
                    Message = "Kullanıcı sisteme tanımlı değil, sisteme dahil olması gerekmektedir."
                };
            }

            return(apiUsers);
        }
Beispiel #4
0
        /// <summary>Instantiates new MangoPayApi object.</summary>
        public MangoPayApi()
        {
            // default config setup
            Config            = new Configuration();
            OAuthTokenManager = new AuthorizationTokenManager(this);

            // API managers initialization
            AuthenticationManager = new ApiOAuth(this);
            Clients               = new ApiClients(this);
            Users                 = new ApiUsers(this);
            Wallets               = new ApiWallets(this);
            PayIns                = new ApiPayIns(this);
            PayOuts               = new ApiPayOuts(this);
            Refunds               = new ApiRefunds(this);
            Transfers             = new ApiTransfers(this);
            CardRegistrations     = new ApiCardRegistrations(this);
            Cards                 = new ApiCards(this);
            Events                = new ApiEvents(this);
            CardPreAuthorizations = new ApiCardPreAuthorizations(this);
            Hooks                 = new ApiHooks(this);
            Kyc              = new ApiKyc(this);
            Disputes         = new ApiDisputes(this);
            Idempotency      = new ApiIdempotency(this);
            Mandates         = new ApiMandates(this);
            Reports          = new ApiReports(this);
            SingleSignOns    = new ApiSingleSignOns(this);
            PermissionGroups = new ApiPermissionGroups(this);
            BankingAlias     = new ApiBankingAliases(this);
            UboDeclarations  = new ApiUboDeclarations(this);
        }
        public string Login(ApiUsers user)
        {
            List <Object> resp = new List <object>();

            if (user.Email == null || user.Pass == null)
            {
                resp.Add(new { status = "failure", message = "Email and Password is mandatory and cannot be null." });
                return(JsonSerializer.Serialize(resp));
            }

            bool   isAuthenticated = false;
            string constr          = Configuration.GetConnectionString("accountsDatabase");
            string query           = "SELECT acc_id,Priv from api_users WHERE Email=@email AND Pass=@pass";

            try
            {
                string?acc_id = null;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand(query))
                    {
                        cmd.Parameters.AddWithValue("@email", user.Email);
                        cmd.Parameters.AddWithValue("@pass", user.Pass);
                        cmd.Connection = con;
                        con.Open();
                        using (SqlDataReader sdr = cmd.ExecuteReader())
                        {
                            if (sdr.HasRows)
                            {
                                isAuthenticated = true;
                                while (sdr.Read())
                                {
                                    acc_id = Convert.ToString(sdr["acc_id"]);
                                }
                            }
                            con.Close();
                        }
                    }
                }
                if (isAuthenticated)
                {
                    string skey = Configuration.GetValue <String>("JwtKey");
                    resp.Add(new { status = "success", token = new JWTToken().getToken(acc_id, skey) });
                    return(JsonSerializer.Serialize(resp));
                }
                else
                {
                    resp.Add(new { status = "failure", message = "Invalid Email or Password." });
                    return(JsonSerializer.Serialize(resp));
                }
            }
            catch (Exception)
            {
                resp.Add(new { status = "failure", message = "Some Unknown Error Occured While Logging in." });
                return(JsonSerializer.Serialize(resp));
            }
        }
Beispiel #6
0
        public async Task <ActionResult> Authenticate([FromBody] ApiUsers model)
        {
            _logger.LogInformation("Authenticate user:{0} pass:{1}", model.Username, model.Password);

            var user = await _userService.Authenticate(model.Username, model.Password);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            _logger.LogInformation("Authenticate userid:{0}", user.UserId);
            return(Ok(user));
        }
        public string ForgotPass(ApiUsers user)
        {
            List <Object> resp   = new List <object>();
            string        constr = Configuration.GetConnectionString("accountsDatabase");
            string        query  = "SELECT acc_id FROM api_users WHERE Email=@email";

            try
            {
                string?acc_id = null;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand(query))
                    {
                        cmd.Parameters.AddWithValue("@email", user.Email);
                        cmd.Connection = con;
                        con.Open();
                        using (SqlDataReader sdr = cmd.ExecuteReader())
                        {
                            while (sdr.Read())
                            {
                                acc_id = Convert.ToString(sdr["acc_id"]);
                            }
                            con.Close();
                        }
                    }
                }
                if (acc_id != null)
                {
                    resp.Add(new { status = "success", message = "OTP Sent successfully to registered mobile and email for account " + acc_id +
                                                                 ". Enter OTP to Reset Password" });
                    return(JsonSerializer.Serialize(resp));
                }
                else if (acc_id == null)
                {
                    resp.Add(new { status = "failure", message = "Provided email id doesn't exist in our records." });
                    return(JsonSerializer.Serialize(resp));
                }
                else
                {
                    resp.Add(new { status = "failure", message = "Some unknown error occured." });
                    return(JsonSerializer.Serialize(resp));
                }
            }
            catch (Exception)
            {
                resp.Add(new { status = "failure", message = "Some Error Occured While Creating Account." });
                return(JsonSerializer.Serialize(resp));
            }
        }
Beispiel #8
0
        public async Task <ActionResult> PostUsers(ApiUsers users)
        {
            try
            {
                var resource = ApiMapper.MapUsers(users);

                await _repo.AddUserAsync(resource);

                return(Ok("User added!"));
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message));
            }
        }
Beispiel #9
0
        protected Dictionary<int, Dictionary<string, object>> UserResultsDictionary(ApiUsers apiUser = ApiUsers.Albers, string platoNameOverride = null, string passwordOverride = null)
        {
            var results = new List<object>();
            var content = SinglePageOfUserResultsDictionary(results, null, apiUser, platoNameOverride, passwordOverride);
            Assert.IsTrue(content.ContainsKey("count"), "content has count property");
            var totalCount = Convert.ToInt32(content["count"].ToString());
            var prevCount = results.Count;

            Console.WriteLine();
            Console.WriteLine("Count --> {0} of {1}", results.Count, totalCount);
            Console.WriteLine();
            Console.WriteLine();

            while (results.Count < totalCount)
            {
                content = SinglePageOfUserResultsDictionary(results, content["__next"].ToString().Split('?')[1], apiUser);
                if (prevCount >= results.Count)
                {
                    Assert.Fail("Results count is not increasing.");
                }
                prevCount = results.Count;

                Console.WriteLine();
                Console.WriteLine("Count --> {0} of {1}", results.Count, totalCount);
                Console.WriteLine();
                Console.WriteLine();
            }

            // note: results contains all pages
            Assert.AreEqual(results.Count, totalCount, "result count matches count property");

            var resultsDictionary = new Dictionary<int, Dictionary<string, object>>();
            foreach (var user in results)
            {
                var userObj = JsonConvert.DeserializeObject<Dictionary<string, object>>(user.ToString());
                resultsDictionary.Add(Convert.ToInt32(userObj["UserId"]), userObj);
            }

            //if (apiUser == ApiUsers.Albers && RequestFactory.DbEnvironment == ApiServiceEnvironment.Test4)
            //{
            //    foreach (var user in resultsDictionary)
            //    {
            //        Console.WriteLine("userId: {0}, role: {1}", user.Key, user.Value["Role"]);
            //    }
            //}

            return resultsDictionary;
        }
Beispiel #10
0
        protected List<Dictionary<string, object>> ProgramsList(ApiUsers apiUser = ApiUsers.Albers)
        {
            var tokenRequest = RequestFactory.NewTokenRequest(apiUser);
            var token = tokenRequest.AssertValidToken();
            var getRequest = RequestFactory.NewGetProgramsRequest(token);
            var response = getRequest.Execute();

            var content = response.AssertValidRestResponse();
            Assert.IsTrue(content.ContainsKey("Results"), "content has Results property");
            var results = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(content["Results"].ToString());

            Assert.IsTrue(content.ContainsKey("count"), "content has count property");
            Assert.AreEqual(results.Count, Convert.ToInt32(content["count"].ToString()), "result count matches count property");

            return results;
        }
        public string Delete(ApiUsers user)
        {
            List <Object> resp       = new List <object>();
            var           curretUser = HttpContext.User;
            string        acc_id     = Convert.ToString(curretUser.FindFirst("id").Value);

            string constr = Configuration.GetConnectionString("accountsDatabase");
            string query  = "DELETE FROM api_users WHERE Email=@email AND acc_id=@acc_id";

            try
            {
                int deleted = 0;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand(query))
                    {
                        cmd.Parameters.AddWithValue("@email", user.Email);
                        cmd.Parameters.AddWithValue("@acc_id", acc_id);
                        cmd.Connection = con;
                        con.Open();
                        deleted = cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }

                if (deleted != 0)
                {
                    resp.Add(new { status = "success", message = Convert.ToString(deleted) + " user account with email " + user.Email + " has been deleted." });
                    return(JsonSerializer.Serialize(resp));
                }
                else
                {
                    resp.Add(new { status = "failure", message = Convert.ToString(deleted) + " Rows affected. " + user.Email + " does not exist or you are not authorized to delete this account" });
                    return(JsonSerializer.Serialize(resp));
                }
            }
            catch (Exception)
            {
                resp.Add(new { status = "failure", message = "Some Error Occured While Deleting Account" });
                return(JsonSerializer.Serialize(resp));
            }
        }
        public string ResetPass(ApiUsers user)
        {
            List <Object> resp   = new List <object>();
            string        constr = Configuration.GetConnectionString("accountsDatabase");


            string query = "UPDATE api_users SET Pass=@Pass WHERE acc_id=@acc_id";

            try
            {
                int changed = 0;
                using (SqlConnection con = new SqlConnection(constr))
                {
                    using (SqlCommand cmd = new SqlCommand(query))
                    {
                        cmd.Parameters.AddWithValue("@Pass", user.Pass);
                        cmd.Parameters.AddWithValue("@acc_id", Convert.ToString(user.acc_id));
                        cmd.Connection = con;
                        con.Open();
                        changed = cmd.ExecuteNonQuery();
                        con.Close();
                    }
                }

                if (changed > 0)
                {
                    resp.Add(new { status = "success", message = "Password changed successfully. Login Again." });
                    return(JsonSerializer.Serialize(resp));
                }
                else
                {
                    resp.Add(new { status = "failure", message = "Password was not changed. Check the input you have given and try again." });
                    return(JsonSerializer.Serialize(resp));
                }
            }
            catch (Exception ex)
            {
                resp.Add(new { status = "failure", message = "Some Error Occured While Changing Password." + ex.Message });
                return(JsonSerializer.Serialize(resp));
            }
        }
Beispiel #13
0
        /// <summary>Instantiates new MangoPayApi object.</summary>
        public MangoPayApi()
        {
            // default config setup
            Config            = new Configuration();
            OAuthTokenManager = new AuthorizationTokenManager(this);

            // API managers initialization
            AuthenticationManager = new ApiOAuth(this);
            Clients               = new ApiClients(this);
            Users                 = new ApiUsers(this);
            Wallets               = new ApiWallets(this);
            PayIns                = new ApiPayIns(this);
            PayOuts               = new ApiPayOuts(this);
            Refunds               = new ApiRefunds(this);
            Transfers             = new ApiTransfers(this);
            CardRegistrations     = new ApiCardRegistrations(this);
            Cards                 = new ApiCards(this);
            Events                = new ApiEvents(this);
            CardPreAuthorizations = new ApiCardPreAuthorizations(this);
            Hooks                 = new ApiHooks(this);
        }
Beispiel #14
0
        private Dictionary<string, object> SinglePageOfUserResultsDictionary(List<object> results, string query, ApiUsers apiUser, string platoNameOverride = null, string passwordOverride = null)
        {
            var tokenRequest = RequestFactory.NewTokenRequest(apiUser, platoNameOverride, passwordOverride);
            var token = tokenRequest.AssertValidToken();
            var getRequest = RequestFactory.NewGetUsersRequest(token, query);
            var response = getRequest.Execute();

            var content = response.AssertValidRestResponse();
            Assert.IsTrue(content.ContainsKey("Results"), "content has Results property");
            var jsonResults = JsonConvert.DeserializeObject<List<object>>(content["Results"].ToString());
            results.AddRange(jsonResults);

            return content;
        }
Beispiel #15
0
        public TokenRequest NewTokenRequest(ApiUsers user = ApiUsers.Albers, string platoNameOverride = null, string passwordOverride = null)
        {
            TokenRequest tokenRequest = null;
            switch (user)
            {
                case ApiUsers.Albers:
                    switch (DbEnvironment)
                    {
                        case ApiServiceEnvironment.Test7:
                            tokenRequest = new TokenRequest(Environment,
                                                            "A4026D22-2822-4310-BCAD-43BB83873EB8",
                                                            "DAC9D40B-BD2B-41FF-A761-5179BF0E0C1E",
                                                            "adminAL2@AL2".PlatoNameOverride(platoNameOverride),
                                                            "AL2K4499".PasswordOverride(passwordOverride));
                            break;
                        case ApiServiceEnvironment.Test4:
                            tokenRequest = new TokenRequest(Environment,
                                                            "0FD590D8-317B-406A-9374-FECD8495AB4C",
                                                            "4690962C-D886-434E-BDF2-A96877F696A9",
                                                            "adminALBERS@ALBERS".PlatoNameOverride(platoNameOverride),
                                                            "ALBE6950".PasswordOverride(passwordOverride));
                            break;
                        default:
                            break;
                    }
                    break;

                case ApiUsers.Javed:
                    switch (DbEnvironment)
                    {
                        case ApiServiceEnvironment.Test7:
                            tokenRequest = new TokenRequest(Environment,
                                                   "C9E11860-3D32-48C4-B56D-ECD4B17F2200",
                                                    "458E3AE0-F284-4A02-8D01-420FFCD48CDD",
                                                    "hca@hca".PlatoNameOverride(platoNameOverride),
                                                    "hca".PasswordOverride(passwordOverride));
                            break;
                        case ApiServiceEnvironment.Test4:
                            tokenRequest = new TokenRequest(Environment,
                                                   "AE1FD2DC-CC6B-42D3-A365-0AC994FD6A72",
                                                    "E86ACA78-E638-4EC5-96FB-10F88E24A831",
                                                    "hca@hca".PlatoNameOverride(platoNameOverride),
                                                    "hca".PasswordOverride(passwordOverride));
                            break;
                        default:
                            break;
                    }
                    break;

                case ApiUsers.AccountAdmin:
                    switch (DbEnvironment)
                    {
                        case ApiServiceEnvironment.Test7:
                            tokenRequest = new TokenRequest(Environment,
                                                   "62B0D107-FA84-411D-B056-B536C11AADC1",
                                                    "D5374B8E-E83F-4BB7-B25D-4210EBBED0AA",
                                                    "apidemo@APIDEMO".PlatoNameOverride(platoNameOverride),
                                                    "apidemo".PasswordOverride(passwordOverride));
                            break;
                        case ApiServiceEnvironment.Test4:
                        default:
                            break;
                    }
                    break;

                case ApiUsers.ProgramAdmin:
                    switch (DbEnvironment)
                    {
                        case ApiServiceEnvironment.Test7:
                            tokenRequest = new TokenRequest(Environment,
                                                   "62B0D107-FA84-411D-B056-B536C11AADC1",
                                                    "D5374B8E-E83F-4BB7-B25D-4210EBBED0AA",
                                                    "pa1@APIDEMO".PlatoNameOverride(platoNameOverride),
                                                    "pa1".PasswordOverride(passwordOverride));
                            break;
                        case ApiServiceEnvironment.Test4:
                            tokenRequest = new TokenRequest(Environment,
                                                   "E1E1D355-187B-4C18-A373-C0E5ED5C9D5C",
                                                    "35B2A853-7A8E-47E7-A2C4-3D6015392F8B",
                                                    "pa4@APIDEMO".PlatoNameOverride(platoNameOverride),
                                                    "pa4".PasswordOverride(passwordOverride));
                            break;
                        default:
                            break;
                    }
                    break;

                case ApiUsers.OpenProgramAdmin:
                    switch (DbEnvironment)
                    {
                        case ApiServiceEnvironment.Test4:
                            tokenRequest = new TokenRequest(Environment,
                                                   "E1E1D355-187B-4C18-A373-C0E5ED5C9D5C",
                                                    "35B2A853-7A8E-47E7-A2C4-3D6015392F8B",
                                                    "pa4@APIDEMO".PlatoNameOverride(platoNameOverride),
                                                    "pa4".PasswordOverride(passwordOverride));
                            break;
                        case ApiServiceEnvironment.Test7:
                        default:
                            break;
                    }
                    break;

                case ApiUsers.Teacher:
                    switch (DbEnvironment)
                    {
                        case ApiServiceEnvironment.Test7:
                            tokenRequest = new TokenRequest(Environment,
                                           "62B0D107-FA84-411D-B056-B536C11AADC1",
                                            "D5374B8E-E83F-4BB7-B25D-4210EBBED0AA",
                                            "ins1@APIDEMO".PlatoNameOverride(platoNameOverride),
                                            "ins1".PasswordOverride(passwordOverride));
                            break;
                        case ApiServiceEnvironment.Test4:
                            tokenRequest = new TokenRequest(Environment,
                                           "0FD590D8-317B-406A-9374-FECD8495AB4C",
                                            "4690962C-D886-434E-BDF2-A96877F696A9",
                                            "ins1@ALBERS".PlatoNameOverride(platoNameOverride),
                                            "ins1".PasswordOverride(passwordOverride));
                            break;
                        default:
                            break;
                    }
                    break;

                case ApiUsers.Learner:
                    switch (DbEnvironment)
                    {
                        case ApiServiceEnvironment.Test7:
                            tokenRequest = new TokenRequest(Environment,
                                           "62B0D107-FA84-411D-B056-B536C11AADC1",
                                            "D5374B8E-E83F-4BB7-B25D-4210EBBED0AA",
                                            "student1@APIDEMO".PlatoNameOverride(platoNameOverride),
                                            "student1".PasswordOverride(passwordOverride));
                            break;
                        case ApiServiceEnvironment.Test4:
                        default:
                            break;
                    }
                    break;

                default:
                    throw new ArgumentOutOfRangeException("user", user, null);
            }

            if (null == tokenRequest)
            {
                Assert.Fail("DbEnvironment {0} does not have a test user {1}", DbEnvironment, user);
            }

            return tokenRequest;
        }
        private Dictionary<string, object> CreateNewUser(string role = "Teacher", ApiUsers apiUser = ApiUsers.Albers)
        {
            var user = new
            {
                PlatoName = Extensions.SmallGuid(),
                FirstName = Extensions.SmallGuid(),
                LastName = Extensions.SmallGuid(),
                MiddleName = Extensions.SmallGuid(),
                StateId = Extensions.SmallGuid(),
                FederalId = Extensions.SmallGuid(),
                Role = role,
                Password = "******",
                IsActive = true,
                Grade = 100
            };

            var tokenRequest = RequestFactory.NewTokenRequest(apiUser);
            var token = tokenRequest.AssertValidToken();
            var postRequest = RequestFactory.NewCreateUserRequest(token, user);
            var response = postRequest.Execute();

            var content = response.AssertValidRestResponse();
            return content;
        }
        public string Create(ApiUsers postdata)
        {
            List <Object> resp = new List <Object>();

            if (postdata.Email == null || postdata.Name == null || postdata.Pass == null)
            {
                return("Name and Email is mandatory and cannot be null. ");
            }

            else
            {
                if (postdata.Mobile == null)
                {
                    postdata.Mobile = 0;
                }
                if (postdata.Company == null)
                {
                    postdata.Company = "null";
                }

                if (postdata.level_priv == null)
                {
                    postdata.level_priv = "user";
                }

                string constr = Configuration.GetConnectionString("accountsDatabase");
                string query  = "INSERT INTO api_users(Name, Email, Pass, Mobile, Company, Priv, acc_id)" +
                                "VALUES (@name, @email, @pass, @mob, @company, @Priv, @Acc_id)";
                try
                {
                    using (SqlConnection con = new SqlConnection(constr))
                    {
                        using (SqlCommand cmd = new SqlCommand(query))
                        {
                            cmd.Parameters.AddWithValue("@name", postdata.Name);
                            cmd.Parameters.AddWithValue("@email", postdata.Email);
                            cmd.Parameters.AddWithValue("@pass", postdata.Pass);
                            cmd.Parameters.AddWithValue("@mob", postdata.Mobile);
                            cmd.Parameters.AddWithValue("@company", postdata.Company);
                            cmd.Parameters.AddWithValue("@Priv", postdata.level_priv);
                            cmd.Parameters.AddWithValue("@Acc_id", rnd.Next(11212, 999999));
                            cmd.Connection = con;
                            con.Open();
                            cmd.ExecuteScalar();
                            con.Close();
                        }
                    }
                    resp.Add(new { status = "success", message = "Account Create successfully!." });
                    return(JsonSerializer.Serialize(resp));
                }

                catch (SqlException ex)
                {
                    if (ex.Number == 2627)
                    {
                        resp.Add(new { status = "failure", message = "An account with provided email Id/Mobile number already exists. Please Login or use another email/Mobile" });
                        return(JsonSerializer.Serialize(resp));
                    }
                    else
                    {
                        resp.Add(new { status = "failure", message = "An unknown error occured. Try again." });
                        return(JsonSerializer.Serialize(resp));
                    }
                }
            }
        }
Beispiel #18
0
        public async Task <bool> ValidateUser(LoginUserDTO userDTO)
        {
            _user = await _userManager.FindByNameAsync(userDTO.Email);

            return(_user != null && await _userManager.CheckPasswordAsync(_user, userDTO.Password));
        }