public async Task <IActionResult> Post([FromBody] ApiUserModel model)
        {
            if (model == null)
            {
                return(BadRequest("Failed: HTTP request body is required."));
            }

            var signIn = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, false, false);

            if (signIn.Succeeded)
            {
                var appUser = _userManager.Users.SingleOrDefault(r => r.UserName == model.UserName);

                string token = await GenerateJwtTokenAsync(appUser);

                var result = new ApiUserModel {
                    Token = token, Id = appUser.Id, UserName = appUser.UserName, Email = appUser.Email
                };

                _telemetryClient.TrackEvent("Successful login.");

                return(Ok(result));
            }

            _telemetryClient.TrackEvent("Failed login.");

            return(Unauthorized());
        }
Beispiel #2
0
        public ApiUserModel AuthUser(string email, string password)
        {
            // string token = "";
            ApiUserModel user = new ApiUserModel();

            try
            {
                Website.Instance.logger.Info($"WMS AuthUser Start! B2D email:{email},pwd:{password}");
                //1. 從IS4取使用者的門票
                // GetTokenResponseModel response = AuthProxy.getToke(account, password);
                //  token = response.access_token ?? response.error_description;

                //1. 從DB抓使用者資訊
                user = UserRepository.GetUser(email, password);

                //3. 把使用者的資訊轉成byte 存進去redis快取
                //  var userByte = ObjectToByteArray(user);

                //  redisCache.Set("wms.api.token", userByte,
                //                new DistributedCacheEntryOptions() {
                //     AbsoluteExpiration = DateTime.Now.AddHours(24)
                //設定過期時間,時間一到快取立刻就被移除
                // });
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(user);
        }
Beispiel #3
0
        /// <summary>
        /// Gets the API user.抓API使用者的資訊
        /// </summary>
        /// <returns>The API user.</returns>
        /// <param name="email">email.</param>
        public static ApiUserModel GetApiUser(string email)
        {
            ApiUserModel aum = new ApiUserModel();

            try {
                JObject obj = UserDAL.GetApiUser(email);

                if (obj != null && obj.Count > 0)
                {
                    aum.result     = "00";
                    aum.result_msg = "OK";
                    aum.user_xid   = (Int64)obj["Table"][0]["xid"];
                    aum.user_name  = obj["Table"][0]["name_first"].ToString()
                                     + obj["Table"][0]["name_last"].ToString();
                    aum.user_email       = obj["Table"][0]["email"].ToString();
                    aum.company_xid      = (Int64)obj["Table"][0]["company_xid"];
                    aum.comapny_name     = obj["Table"][0]["comp_name"].ToString();
                    aum.company_language = obj["Table"][0]["comp_locale"].ToString();
                    aum.company_currency = obj["Table"][0]["comp_currency"].ToString();
                    aum.payment_type     = obj["Table"][0]["payment_type"].ToString();
                }
                else
                {
                    //若帳密有誤 僅傳送錯誤代碼
                    aum.result     = "03";
                    aum.result_msg = "Unauthorized";
                }
            } catch (Exception ex) {
                Website.Instance.logger.FatalFormat($"getApiUser  Error :{ex.Message},{ex.StackTrace}");

                throw ex;
            }

            return(aum);
        }
        public async Task LoginControllerTestValidLogin()
        {
            string password = "******";

            var expected = new ApplicationUser
            {
                UserName = Guid.NewGuid().ToString(),
                Email    = $"{Guid.NewGuid()}@host.com",
            };

            var created = await UserManager.CreateAsync(expected, password);

            Assert.IsTrue(created.Succeeded);

            var target = new LoginController(UserManager, new FakeSignInManager(UserManager), ConfigMock.Object);

            var request = new ApiUserModel {
                UserName = expected.UserName, Password = password
            };

            var response = (OkObjectResult)await target.Post(request);

            Assert.AreEqual(200, response.StatusCode);

            var actual = (ApiUserModel)response.Value;

            Assert.AreEqual(expected.UserName, actual.UserName);
            Assert.AreEqual(expected.Email, actual.Email);
            Assert.AreEqual(Context.Users.SingleAsync().Result.Id, actual.Id);
            Assert.IsTrue(actual.Token.Length > 1);
        }
Beispiel #5
0
        public async Task AccountControllerTestCreate()
        {
            var target = new AccountController(UserManager, ConfigMock.Object);

            var request = new ApiUserModel
            {
                UserName = Guid.NewGuid().ToString(),
                Email    = $"{Guid.NewGuid()}@host.com",
                Password = "******"
            };

            var response = (OkObjectResult)await target.Post(request);

            Assert.AreEqual(200, response.StatusCode);

            var actual = (ApiUserModel)response.Value;

            Assert.AreEqual(request.UserName, actual.UserName);
            Assert.AreEqual(request.Email, actual.Email);
            Assert.IsFalse(string.IsNullOrEmpty(actual.Id));
            Assert.IsNotNull(actual.Token);

            var created = await Context.Users.SingleAsync();

            Assert.AreEqual(request.UserName, created.UserName);
            Assert.AreEqual(request.Email, created.Email);
            Assert.AreEqual(created.Id, actual.Id);

            bool passwordOk = await UserManager.CheckPasswordAsync(created, request.Password);

            Assert.IsTrue(passwordOk);
        }
        public ApiUserModel GetApiUserById(int id)
        {
            ApiUser      apiUser      = db.ApiUsers.Where(account => account.ApiUserId == id).FirstOrDefault();
            ApiUserModel apiUserModel = Utilities.ApiUserToApiUserModel(apiUser);

            return(apiUserModel);
        }
        public ApiUserModel GetApiUserByEmail(string email)
        {
            ApiUser      apiUser      = db.ApiUsers.Where(account => account.Email == email).FirstOrDefault();
            ApiUserModel apiUserModel = Utilities.ApiUserToApiUserModel(apiUser);

            return(apiUserModel);
        }
        public ApiUserModel GetApiUserByApiKey(string apiKey)
        {
            ApiUser      apiUser      = db.ApiUsers.Where(account => account.ApiKey == apiKey).FirstOrDefault();
            ApiUserModel apiUserModel = Utilities.ApiUserToApiUserModel(apiUser);

            return(apiUserModel);
        }
        public async Task <IActionResult> Post([FromBody] ApiUserModel model)
        {
            if (model == null)
            {
                return(BadRequest("Failed: HTTP request body is required."));
            }

            if (model.Password == null)
            {
                return(BadRequest("Failed: Password is required."));
            }

            var user = new ApplicationUser {
                UserName = model.UserName, Email = model.Email
            };

            var result = await _userManager.CreateAsync(user, model.Password);

            if (!result.Succeeded)
            {
                return(BadRequest(result.ToString()));
            }

            ApiUserModel response = new ApiUserModel {
                Email = user.Email, Id = user.Id, UserName = user.UserName
            };

            _telemetryClient.TrackEvent("User created.");

            return(Ok(response));
        }
        public async Task LoginControllerTestWrongPassword()
        {
            string password = "******";

            var expected = new ApplicationUser
            {
                UserName = Guid.NewGuid().ToString(),
                Email    = $"{Guid.NewGuid()}@host.com",
            };

            var created = await UserManager.CreateAsync(expected, password);

            Assert.IsTrue(created.Succeeded);

            var config = new Mock <IConfiguration>();

            var target = new LoginController(UserManager, SignInManager, config.Object);

            var request = new ApiUserModel {
                UserName = expected.UserName, Password = "******"
            };

            var actual = (UnauthorizedResult)target.Post(request).Result;

            Assert.AreEqual(401, actual.StatusCode);
        }
        public async Task LoginControllerTestAbsentUser()
        {
            var target = new LoginController(UserManager, SignInManager, ConfigMock.Object);

            var request = new ApiUserModel {
                UserName = "******", Password = "******"
            };

            var actual = (UnauthorizedResult)await target.Post(request);

            Assert.AreEqual(401, actual.StatusCode);
        }
Beispiel #12
0
        public async Task AccountControllerTestCreateNoUsername()
        {
            var target = new AccountController(UserManager);

            var request = new ApiUserModel
            {
                Email    = $"{Guid.NewGuid()}@host.com",
                Password = "******"
            };

            var response = (BadRequestObjectResult)await target.Post(request);

            Assert.AreEqual(400, response.StatusCode);
        }
Beispiel #13
0
        public async Task AccountControllerTestCreateNoPassword()
        {
            var target = new AccountController(UserManager);

            var request = new ApiUserModel
            {
                UserName = Guid.NewGuid().ToString(),
                Email    = $"{Guid.NewGuid()}@host.com",
            };

            var response = (BadRequestObjectResult)await target.Post(request);

            Assert.AreEqual(400, response.StatusCode);
        }
Beispiel #14
0
        public async Task AccountControllerTestCreateNoEmail()
        {
            var target = new AccountController(UserManager, ConfigMock.Object);

            var request = new ApiUserModel
            {
                UserName = Guid.NewGuid().ToString(),
                Password = "******"
            };

            var response = (BadRequestObjectResult)await target.Post(request);

            Assert.AreEqual(400, response.StatusCode);
        }
Beispiel #15
0
        public async Task AccountControllerTestChangePassword()
        {
            string password = "******";
            string email    = $"{Guid.NewGuid()}@host.com";

            var user = new ApplicationUser
            {
                UserName = Guid.NewGuid().ToString(),
                Email    = email,
            };

            var created = await UserManager.CreateAsync(user, password);

            Assert.IsTrue(created.Succeeded);

            user = await Context.Users.SingleAsync();

            var target = new AccountController(UserManager, ConfigMock.Object);

            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                new Claim(ClaimTypes.NameIdentifier, user.Id)
            };

            var principal = new ClaimsPrincipal(new ClaimsIdentity(claims));

            target.ControllerContext = new ControllerContext()
            {
                HttpContext = new DefaultHttpContext()
                {
                    User = principal
                }
            };

            var request = new ApiUserModel {
                Password = password, NewPassword = "******"
            };

            var response = (OkResult)await target.Put(request);

            Assert.AreEqual(200, response.StatusCode);

            Assert.AreEqual(email, user.Email); // email should not change

            bool passwordChanged = await UserManager.CheckPasswordAsync(user, request.NewPassword);

            Assert.IsTrue(passwordChanged);
        }
Beispiel #16
0
        public ApiUserModel AuthApiUser(string email)
        {
            ApiUserModel ApiUser = new ApiUserModel();

            try
            {
                Website.Instance.logger.Info($"WMS AuthApiUser Start! B2D email:{email}");
                //從DB抓使用者資訊
                ApiUser = UserRepository.GetApiUser(email);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(ApiUser);
        }
Beispiel #17
0
 /// <summary>
 /// 修改密码
 /// </summary>
 /// <param name="userName"></param>
 /// <param name="oldPwd"></param>
 /// <param name="newPwd"></param>
 /// <returns></returns>
 public JsonResult UpdatePwd(string userName, string oldPwd, string newPwd)
 {
     try
     {
         ApiUserModel model = new ApiUserModel();
         model.UserName    = userName;
         model.OldPassWord = oldPwd;
         model.NewPassWord = newPwd;
         bool result = servPersonInfoBLL.UpdatePwd(model);
         return(Json(new { status = 0, msg = result }));
     }
     catch (Exception ex)
     {
         return(Json(new { status = 1, msg = ex.Message }));
     }
 }
Beispiel #18
0
        public async Task <IReadOnlyCollection <ReleaseModel> > GetNewReleases(ApiUserModel apiUser, CancellationToken cancellationToken)
        {
            var request = new NewReleasesRequest
            {
                UserId = apiUser.Id,
            };

            var response = await serviceClient.GetNewReleasesAsync(request, cancellationToken : cancellationToken);

            return(response.NewReleases.Select(x => new ReleaseModel
            {
                Id = new IdModel(x.Id),
                Year = x.Year,
                Title = x.Title,
            })
                   .ToList());
        }
Beispiel #19
0
 /// <summary>
 /// 修改密码
 /// </summary>
 /// <param name="model"></param>
 /// <returns></returns>
 public bool UpdatePwd(ApiUserModel model)
 {
     try
     {
         string parStr = JsonHelper.ObjectToString <ApiUserModel>(model);
         string str    = HttpHelper.PostWebRequestBandError("http://" + personIp + "/ApiPersonInfo/UpdatePassWordRetNumber", parStr, "application/json;charset=utf-8", Encoding.UTF8);
         int    result = JsonHelper.StringToObject <int>(str);
         bool   re     = true;
         if (result == 1)
         {
             re = false;
         }
         return(re);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        public async Task <IActionResult> Put([FromBody] ApiUserModel model)
        {
            if (model == null)
            {
                return(BadRequest("Failed: HTTP request body is required."));
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            if (!string.IsNullOrEmpty(model.NewPassword))
            {
                var changePasswordResult = await _userManager.ChangePasswordAsync(user, model.Password, model.NewPassword);

                if (!changePasswordResult.Succeeded)
                {
                    return(BadRequest(changePasswordResult.ToString()));
                }

                return(Ok());
            }
            else if (!string.IsNullOrEmpty(model.Email))
            {
                //await _acountManager.ChangeEmail(user, model.Email);
                if (user.Email != model.Email)
                {
                    var setEmailResult = await _userManager.SetEmailAsync(user, model.Email);

                    if (!setEmailResult.Succeeded)
                    {
                        return(BadRequest(setEmailResult.ToString()));
                    }
                }
                return(Ok());
            }

            return(BadRequest());
        }
Beispiel #21
0
        /// <summary>
        /// Gets the user.抓一般使用者資訊
        /// </summary>
        /// <returns>The user.</returns>
        /// <param name="email">email.</param>
        /// <param name="pw">Pw.</param>
        public static ApiUserModel GetUser(string email, string pw)
        {
            ApiUserModel aum = new ApiUserModel();

            try {
                //1.將明碼加密
                SHA256 sha256   = new SHA256CryptoServiceProvider(); //建立一個SHA256
                byte[] source   = Encoding.Default.GetBytes(pw);     //將字串轉為Byte[]
                byte[] crypto   = sha256.ComputeHash(source);        //進行SHA256加密
                var    chiperPW = Convert.ToBase64String(crypto);    //把加密後的字串從Byte[]轉為字串

                //2.檢查登入者身分
                JObject obj = UserDAL.GetUser(email, chiperPW);

                if (obj != null && obj.Count > 0)
                {
                    aum.result     = "00";
                    aum.result_msg = "OK";
                    aum.user_xid   = (Int64)obj["Table"][0]["xid"];
                    aum.user_name  = obj["Table"][0]["name_first"].ToString()
                                     + obj["Table"][0]["name_last"].ToString();
                    aum.user_email       = obj["Table"][0]["email"].ToString();
                    aum.company_xid      = (Int64)obj["Table"][0]["company_xid"];
                    aum.comapny_name     = obj["Table"][0]["comp_name"].ToString();
                    aum.company_language = obj["Table"][0]["comp_locale"].ToString();
                    aum.company_currency = obj["Table"][0]["comp_currency"].ToString();
                    aum.payment_type     = obj["Table"][0]["payment_type"].ToString();
                }
                else
                {
                    //若帳密有誤 僅傳送錯誤代碼
                    aum.result     = "03";
                    aum.result_msg = "Unauthorized";
                }
            } catch (Exception ex) {
                Website.Instance.logger.FatalFormat($"getUser  Error :{ex.Message},{ex.StackTrace}");

                throw ex;
            }

            return(aum);
        }
Beispiel #22
0
        public async Task AccountControllerTestChangeInvalidEmail()
        {
            string password = "******";

            var user = new ApplicationUser
            {
                UserName = Guid.NewGuid().ToString(),
                Email    = $"{Guid.NewGuid()}@host.com",
            };

            var created = await UserManager.CreateAsync(user, password);

            Assert.IsTrue(created.Succeeded);

            user = await Context.Users.SingleAsync();

            var target = new AccountController(UserManager, ConfigMock.Object);

            var claims = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
                new Claim(ClaimTypes.NameIdentifier, user.Id)
            };

            var principal = new ClaimsPrincipal(new ClaimsIdentity(claims));

            target.ControllerContext = new ControllerContext()
            {
                HttpContext = new DefaultHttpContext()
                {
                    User = principal
                }
            };

            var request = new ApiUserModel {
                Email = "invalid email"
            };

            var response = (BadRequestObjectResult)await target.Put(request);

            Assert.AreEqual(400, response.StatusCode);
        }
        public bool UpdateApiUser(ApiUserModel aum)
        {
            ApiUser apiUser = db.ApiUsers.Where(u => u.ApiUserId == aum.ApiUserId).FirstOrDefault();

            if (apiUser != null)
            {
                apiUser.ApiKey       = aum.ApiKey;
                apiUser.ApiCallCount = aum.ApiCallCount;
                apiUser.LastCallDate = aum.LastCallDate;
                apiUser.AppName      = aum.AppName;
                apiUser.Email        = aum.Email;
                db.SaveChanges();

                return(true);
            }
            else
            {
                return(false);
            }
        }
Beispiel #24
0
 public void Put(int id, [FromBody] ApiUserModel student)
 {
     slotDataAccessLayer.UpdateBooking(id, student.SchoolId);
 }