예제 #1
0
        private async void BtnSave_Clicked(object sender, EventArgs e)
        {
            if (!(this.lblTipsOldPwd.Text == "√" && this.lblTipsNewPwd.Text == "√" && this.lblTipsReNewPwd.Text == "√"))
            {
                return;
            }

            List <Models.UserInfo> list = new List <Models.UserInfo>();

            Models.UserInfo ui = new Models.UserInfo();
            ui.Account  = OptionText_Helper.ReadAllText("Account");
            ui.PassWord = MD5_Helper.MD5Encrypt16(this.etyNewPwd.Text);

            string url = $"/{Version_Helper.versionNumber}/user_/update?Option=PassWord&Account={ui.Account}";

            list.Add(ui);

            var result = await WebApiService_Helper.PostConnectHelperAsync(url, list);

            if (result[0].Flag)
            {
                OptionText_Helper.WriteText("PassWord", ui.PassWord);
                await DisplayAlert("提示!", "修改成功!", "确认");

                await Navigation.PopAsync();
            }
            else
            {
                await DisplayAlert("提示!", "修改失败!", "确认");
            }
        }
        public IActionResult CreateUser([FromBody] Models.CreateUserRequest req)
        {
            var user = new Models.UserInfo(req.UserName, req.EMail, _users.Count != 0 ? _users.Count + 1 : 1);

            _users.Add(user);
            return(Ok(user));
        }
예제 #3
0
        public async Task <ResponseMessage <GiftInfo> > ConsumableScore(Models.UserInfo user, [FromBody] ConsumableScoreRequest request)
        {
            Logger.Trace($"用户{user?.UserName ?? ""}({user?.Id ?? ""})抽奖,请求参数为:\r\n" + JsonHelper.ToJson(request));
            var response = new ResponseMessage <GiftInfo>();

            if (!ModelState.IsValid)
            {
                response.Code    = ResponseCodeDefines.ModelStateInvalid;
                response.Message = "模型验证失败" + ModelState.GetAllErrors();
                Logger.Warn("抽奖模型验证失败:\r\n{0}", response.Message ?? "");
                return(response);
            }
            var prefixs = new string[] { "ConsumableScore" };
            var key     = "ConsumableScore";

            try
            {
                // 防止同时中奖,兑奖,数量不够。所以这里是一个一个来
                await _cache.LockSubmit(prefixs, key, "ConsumableScore", HttpContext.RequestAborted);

                response = await _giftManager.ConsumableScoreAsync(user, request, HttpContext.RequestAborted);
            }
            catch (Exception e)
            {
                response.Code    = ResponseCodeDefines.ServiceError;
                response.Message = e.Message;
                Logger.Error($"用户{user?.UserName ?? ""}({user?.Id ?? ""})抽奖,报错:{e.Message}\r\n{e.StackTrace}");
            }
            finally
            {
                // 成功失败都要移除
                await _cache.UnlockSubmit(prefixs, key);
            }
            return(response);
        }
예제 #4
0
        /// <summary>
        /// 将用户的信息(订阅源列表,收藏)发送至服务器
        /// </summary>
        /// <param name="userInfo"></param>
        static public void UpdateProfile(Models.UserInfo userInfo)
        {
            try
            {
                #region Get data from Internet
                HttpClient httpClient = new HttpClient();

                // Add a user-agent header to the GET request.
                var headers = httpClient.DefaultRequestHeaders;

                // The safe way to add a header value is to use the TryParseAdd method and verify the return value is true,
                // especially if the header value is coming from user input.
                string header = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.86 Safari/537.36";
                if (!headers.UserAgent.TryParseAdd(header))
                {
                    throw new Exception("Invalid header value: " + header);
                }

                httpClient.BaseAddress = new Uri("http://localhost:3000");
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("user", JsonConvert.SerializeObject(userInfo))
                });
                var result = httpClient.PostAsync("/api/profile", content).Result;

                string resultContent = result.Content.ReadAsStringAsync().Result;
                #endregion
                // 确认是否正确返回
                ErrorChecker(resultContent);
            } catch (Exception e)
            {
                var i = new MessageDialog(e.Message).ShowAsync();
            }
        }
예제 #5
0
        public JsonResult Info(string token)
        {
            JsonResult result = null;
            AuthInfo   auth   = _authInfoService.GetAuth(token);

            if (auth.UserInfo != null)
            {
                var user = new Models.UserInfo();
                user.Name         = auth.UserInfo.Name;
                user.Avatar       = auth.UserInfo.Avatar;
                user.Introduction = auth.UserInfo.Introduction;
                user.roles        = new List <string>();
                foreach (var i in auth.UserInfo.Roles)
                {
                    user.roles.Add(i.Name);
                }
                result = new JsonResult(new {
                    code = 20000,
                    data = user
                });
            }
            else
            {
                result = new JsonResult(new {
                    code    = 50008,
                    message = "Login failed, unable to get user details."
                });
            }

            return(result);
        }
예제 #6
0
        public ActionResult Edit(vmUser getuser, FormCollection collection)
        {
            try
            {
                var edituser = new Models.UserInfo();

                edituser = iuser.GetUser(getuser.UserId);

                getuser.Divitions = idv.GetKVP();
                getuser.Districts = idis.GetKVP(0);

                edituser.FristName  = getuser.FristName;
                edituser.LastName   = getuser.LastName;
                edituser.UserName   = getuser.UserName;
                edituser.Email      = getuser.Email;
                edituser.Mobile     = getuser.Mobile;
                edituser.GenderId   = getuser.GenderId;
                edituser.DivitionId = getuser.DivitionId;
                edituser.DistrictId = getuser.DistrictId;
                edituser.LastEducationalQulification = getuser.LastEducationalQulification;
                edituser.Occupation     = getuser.Occupation;
                edituser.PresentAddress = getuser.PresentAddress;
                edituser.DateOFBirth    = getuser.DateOFBirth;


                iuser.UpdateUser(edituser);

                return(RedirectToAction("Index"));
            }
            catch (Exception e)
            {
                return(View(getuser));
            }
        }
예제 #7
0
        public ActionResult Create(FormCollection collection, ViewModel.vmUser user)
        {
            try
            {
                var adduser = new Models.UserInfo();
                user.Divitions     = idv.GetKVP();
                user.Districts     = idis.GetKVP(9);
                adduser.FristName  = user.FristName;
                adduser.LastName   = user.LastName;
                adduser.UserName   = user.UserName;
                adduser.Email      = user.Email;
                adduser.Mobile     = user.Mobile;
                adduser.GenderId   = user.GenderId;
                adduser.DivitionId = user.DivitionId;
                adduser.DistrictId = user.DistrictId;
                adduser.LastEducationalQulification = user.LastEducationalQulification;
                adduser.Occupation     = user.Occupation;
                adduser.PresentAddress = user.PresentAddress;
                adduser.DateOFBirth    = user.DateOFBirth;



                iuser.InserUser(adduser);

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
예제 #8
0
        public async Task <ResponseMessage <TaskDetailsResponse> > TaskDetails(Models.UserInfo user, [FromRoute] string taskId)
        {
            var response = new ResponseMessage <TaskDetailsResponse>();

            Logger.Trace($"用户{user?.UserName ?? ""}({user?.Id ?? ""})K币任务详情,请求参数为:\r\n{JsonHelper.ToJson(taskId)}");
            if (!ModelState.IsValid)
            {
                response.Code    = ResponseCodeDefines.ModelStateInvalid;
                response.Message = ModelState.GetAllErrors();
                Logger.Warn($"用户{user?.UserName ?? ""}({user?.Id ?? ""})K币任务详情,模型验证失败:\r\n{response.Message ?? ""}");
                return(response);
            }
            try
            {
                response = await _taskManager.GetTaskDetailsAsync(user, taskId);
            }
            catch (Exception e)
            {
                Logger.Error($"用户{user?.UserName ?? ""}({user?.Id ?? ""})K币任务详情,报错:{e.Message}\r\n{e.StackTrace}");
                response.Code    = ResponseCodeDefines.ServiceError;
                response.Message = e.Message;
                return(response);
            }

            return(response);
        }
        public ActionResult RegisterInfo(Models.UserInfo info)
        {
            int    Result = 0;
            string message;

            try
            {
                if (ModelState.IsValid)
                {
                    Result = accountBLL.Register(info);
                    if (Result == 1)
                    {
                        message = "You are Successfully Registered";
                    }
                    else
                    {
                        message = "Oops Something went wrong";
                    }
                    return(Json(new { success = true, responseText = message }, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            return(View("Register", info));
        }
예제 #10
0
        public async Task <ResponseMessage> ExamineTask(Models.UserInfo user, [FromBody] ExamineTaskRequest condition)
        {
            Logger.Trace($"用户{user?.UserName ?? ""}({user?.Id ?? ""})管理员审核任务,请求体为:\r\n{JsonHelper.ToJson(condition)}");
            var response = new ResponseMessage();

            var prefixs = new string[] { "TaskController" };
            var key     = $"{user.Id}{condition.TaskId}{condition.IsOk}";

            try
            {
                // 防止重复提交
                await _cache.LockSubmit(prefixs, key, "ExamineTask", HttpContext.RequestAborted);

                response = await _taskManager.ExaminetaskAsync(user, condition);
            }
            catch (Exception e)
            {
                response.Code    = ResponseCodeDefines.ServiceError;
                response.Message = e.Message;
                Logger.Trace($"用户{user?.UserName ?? ""}({user?.Id ?? ""})管理员审核任务,失败:{e.Message}错误堆栈信息:\r\n" + (JsonHelper.ToJson(e.StackTrace)));
            }
            finally
            {
                // 成功失败都要移除
                await _cache.UnlockSubmit(prefixs, key);
            }
            return(response);
        }
예제 #11
0
        public async Task <ResponseMessage> KcoinTaskGrab(Models.UserInfo user, [FromRoute] string taskId)
        {
            var response = new ResponseMessage();

            Logger.Trace($"用户{user?.UserName ?? ""}({user?.Id ?? ""})抢K币任务,请求参数为:\r\n{JsonHelper.ToJson(taskId)}");
            if (!ModelState.IsValid)
            {
                response.Code    = ResponseCodeDefines.ModelStateInvalid;
                response.Message = ModelState.GetAllErrors();
                Logger.Warn($"用户{user?.UserName ?? ""}({user?.Id ?? ""})抢K币任务,模型验证失败:\r\n{response.Message ?? ""}");
                return(response);
            }
            var prefixs = new string[] { "TaskController" };
            var key     = $"{user.Id}{taskId}";

            try
            {
                // 防止重复提交
                await _cache.LockSubmit(prefixs, key, "KcoinTaskGrab", HttpContext.RequestAborted);

                response = await _taskManager.KcoinTaskGrab(user, taskId);
            }
            catch (Exception e)
            {
                response.Code    = ResponseCodeDefines.ServiceError;
                response.Message = e.Message;
                Logger.Error($"用户{user?.UserName ?? ""}({user?.Id ?? ""})抢K币任务,报错:{e.Message}\r\n{e.StackTrace}");
            }
            finally
            {
                // 成功失败都要移除
                await _cache.UnlockSubmit(prefixs, key);
            }
            return(response);
        }
예제 #12
0
        public async Task <ResponseMessage> SaveTaskInfo(Models.UserInfo user, [FromBody] TaskSaveRequest request)
        {
            Logger.Trace($"用户{user?.UserName ?? ""}({user?.Id ?? ""})新增/修改我的任务:{JsonHelper.ToJson(request)}");
            var response = new ResponseMessage();

            if (!ModelState.IsValid)
            {
                response.Code    = ResponseCodeDefines.ModelStateInvalid;
                response.Message = ModelState.GetAllErrors();
                Logger.Warn($"用户{user?.UserName ?? ""}({user?.Id ?? ""})新增/修改我的任务,模型验证失败:\r\n{response.Message ?? ""}");
                return(response);
            }
            try
            {
                response = await _taskManager.SaveTaskInfo(user, request, HttpContext.RequestAborted);
            }
            catch (Exception e)
            {
                Logger.Error($"用户{user?.UserName ?? ""}({user?.Id ?? ""})新增/修改任务,报错:{e.Message}\r\n{e.StackTrace}");
                response.Code    = ResponseCodeDefines.ServiceError;
                response.Message = e.Message;
                return(response);
            }

            return(response);
        }
예제 #13
0
        public static void Initialize(AccountDbContext context)
        {
            context.Database.EnsureCreated();

            // Look for any Users.
            if (context.UserInfo.Any())
            {
                return;   // DB has been seeded
            }

            var userInfo = new Models.UserInfo[]
            {
                new Models.UserInfo {
                    FirstName = "Admin", LastName = "Default", UserName = "******", Email = "*****@*****.**", UserRole = 0, UserGroup = "Admin", Password = "******"
                },
                new Models.UserInfo {
                    FirstName = "Super", LastName = "Default", UserName = "******", Email = "*****@*****.**", UserRole = 1, UserGroup = "Client", UserOwnerId = "1", Password = "******"
                },
                new Models.UserInfo {
                    FirstName = "User", LastName = "Default", UserName = "******", Email = "*****@*****.**", UserRole = 2, UserGroup = "Client", UserOwnerId = "2", Password = "******"
                },
            };

            context.UserInfo.AddRange(userInfo);
            context.SaveChanges();
        }
예제 #14
0
        public object ApiLogin()
        {
            var acc = GetApiObject <Models.AccountBinding>();
            var id  = acc.UserName.ToLower();
            var e   = new AccountController()
                      .Collection
                      .FindById <Models.Account>(id);

            if (e == null)
            {
                return(Error(-1));
            }
            if (e.Password != MD5Hash(id + acc.Password))
            {
                return(Error(-2));
            }

            var token = MD5Hash(id + DateTime.Now);
            var u     = new Models.UserInfo
            {
                Account = e,
                Name    = id,
            };

            new UserController().Collection.Insert(token, u);

            u.Id = token;
            return(Success(u));
        }
예제 #15
0
        private async void changeGoalWeightButton_Clicked(object sender, EventArgs e)
        {
            Models.UserInfo currentUser = App.DatabaseAccess.GetUserInfos()[0];

            int    currentWeight = currentUser.CurrentWeight;
            string inputString   = await DisplayPromptAsync("Enter your new goal weight:", "");

            int newWeight = 0;



            if (!String.IsNullOrEmpty(inputString) && int.TryParse(inputString, out newWeight))
            {
                // If weight is valid, update in database
                if (newWeight >= currentWeight && ReferenceItems.isInConstraints(newWeight, currentUser.MeasurementUnit))
                {
                    currentUser.GoalWeight = newWeight;
                    App.DatabaseAccess.UpdateUser(currentUser);
                    return;
                }

                // Otherwise, display error message
                await DisplayAlert("Error", "Goal weight is either less than your current weight, or out of constraints.", "Okay");
            }

            else
            {
                await DisplayAlert("Error", "Invalid weight entered.", "Okay");
            }
        }
        public ActionResult Register(Models.UserInfo user)
        {
            UserRepository userRepository = new UserRepository();

            Session["code"] = userRepository.Register(user);
            return(RedirectToAction("Confirm"));
        }
예제 #17
0
        private async void VcGender_Tapped(object sender, EventArgs e)
        {
            string Gender = await DisplayActionSheet("请选择您的性别:", "取消", null, "男", "女", "保密");

            if (Gender != "取消" && Gender != null)
            {
                this.lblGender.Text = Gender;

                Models.UserInfo ui = new Models.UserInfo();
                ui.Account = OptionText_Helper.ReadAllText("Account");
                ui.Gender  = Gender;

                List <Models.UserInfo> list = new List <Models.UserInfo>();
                string url = $"/{Version_Helper.versionNumber}/user_/update?Option=Gender&Account={ui.Account}";

                list.Add(ui);

                var result = await WebApiService_Helper.PostConnectHelperAsync(url, list);

                if (result[0].Flag)
                {
                    OptionText_Helper.WriteText("Gender", Gender);
                }
                else
                {
                    await DisplayAlert("提示!", "保存失败!", "确认");
                }
            }
        }
예제 #18
0
        public async Task <ResponseMessage> AllocateSubmit(Models.UserInfo user, [FromBody] AllocateSubmitRequest allocateSubmitRequest)
        {
            Logger.Trace($"用户{user?.UserName ?? ""}({user?.Id ?? ""})新增派发,请求参数为:\r\n" + (allocateSubmitRequest != null ? JsonHelper.ToJson(allocateSubmitRequest) : ""));
            var response = new ResponseMessage();

            if (!ModelState.IsValid)
            {
                response.Code    = ResponseCodeDefines.ArgumentNullError;
                response.Message = "模型验证失败" + ModelState.GetAllErrors();
                Logger.Warn("新增派发模型验证失败:\r\n{0}", response.Message ?? "");
                return(response);
            }
            var prefixs = new string[] { "AllocateController" };
            var key     = $"{user.Id}{allocateSubmitRequest.Theme}{allocateSubmitRequest.Score}";

            try
            {
                // 防止重复提交
                await _cache.LockSubmit(prefixs, key, "AllocateSubmit", HttpContext.RequestAborted);

                response = await _allocateManager.AllocateSubmitAsync(user, allocateSubmitRequest, HttpContext.RequestAborted);
            }
            catch (Exception e)
            {
                response.Code    = ResponseCodeDefines.ServiceError;
                response.Message = e.Message;
                Logger.Error($"用户{user?.UserName ?? ""}({user?.Id ?? ""})新增派发,报错:{e.Message}\r\n{e.StackTrace}");
            }
            finally
            {
                // 成功失败都要移除
                await _cache.UnlockSubmit(prefixs, key);
            }
            return(response);
        }
예제 #19
0
        public ActionResult Chat(DataTable dtUserInfoTemp)
        {
            Models.UserInfo userInfo = new Models.UserInfo();

            if (TempData["userInfo"] == null)
            {
                if (Session["LoginName"] == null)
                {
                    return(RedirectToAction("Index", "Login"));
                }

                String    userPhoneNumber = Session["LoginName"].ToString();
                PubClass  myClass         = new PubClass();
                DataTable dtUserInfo      = myClass.GetUserInfoByPhoneNumber(userPhoneNumber);
                DataRow   drRowUserInfo   = dtUserInfo.Rows[0];

                userInfo.userName        = drRowUserInfo["userName"].ToString();
                userInfo.phoneNumber     = drRowUserInfo["phoneNumber"].ToString();
                userInfo.job             = drRowUserInfo["job"].ToString();
                userInfo.jobIntroduction = drRowUserInfo["jobIntroduction"].ToString();
                userInfo.imgPath         = drRowUserInfo["imgPath"].ToString();
            }
            else
            {
                userInfo = (Models.UserInfo)TempData["userInfo"];
            }


            if (userInfo == null)
            {
                return(RedirectToAction("Index", "Login"));
            }

            return(View(userInfo));
        }
예제 #20
0
        private IActionResult BuildToken(Models.UserInfo userInfo)
        {
            var claims = new[]
            {
                new Claim(JwtRegisteredClaimNames.UniqueName, userInfo.Email),
                new Claim("miValor", "Lo que yo quiera"),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            var key   = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Llave_super_secreta"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var expiration = DateTime.UtcNow.AddHours(1);

            JwtSecurityToken token = new JwtSecurityToken(
                issuer: "yourdomain.com",
                audience: "yourdomain.com",
                claims: claims,
                expires: expiration,
                signingCredentials: creds);

            return(Ok(new
            {
                token = new JwtSecurityTokenHandler().WriteToken(token),
                expiration = expiration
            }));
        }
예제 #21
0
        public async Task <ResponseMessage> Delete(Models.UserInfo user, string id)
        {
            var response = new ResponseMessage();

            Logger.Trace($"用户{user?.UserName ?? ""}({user?.Id ?? ""})删除用户,请求参数为:\r\n{(id != null ? JsonHelper.ToJson(id) : "")}");
            if (!ModelState.IsValid)
            {
                response.Code    = ResponseCodeDefines.ModelStateInvalid;
                response.Message = ModelState.GetAllErrors();
                Logger.Warn($"用户{user?.UserName ?? ""}({user?.Id ?? ""})删除用户,模型验证失败:\r\n{response.Message ?? ""}");
                return(response);
            }

            try
            {
                response = await UserManager.Delete(user, id, HttpContext.RequestAborted);
            }
            catch (Exception e)
            {
                Logger.Error($"用户{user?.UserName ?? ""}({user?.Id ?? ""})删除用户,报错:{e.Message}\r\n{e.StackTrace}");
                response.Code    = ResponseCodeDefines.ServiceError;
                response.Message = e.Message;
                return(response);
            }

            return(response);
        }
예제 #22
0
        public async Task <ResponseMessage> Save(Models.UserInfo user, [FromBody] UserSaveRequest request)
        {
            Logger.Trace($"用户{user?.UserName ?? ""}({user?.Id ?? ""})保存用户,请求参数为:\r\n" + (request != null ? JsonHelper.ToJson(request) : ""));
            var response = new ResponseMessage();

            if (!ModelState.IsValid)
            {
                response.Code    = ResponseCodeDefines.ModelStateInvalid;
                response.Message = ModelState.GetAllErrors();
                Logger.Warn("保存用户模型验证失败:\r\n{0}", response.Message ?? "");
                return(response);
            }

            try
            {
                response = await UserManager.Save(user, request, HttpContext.RequestAborted);
            }
            catch (Exception e)
            {
                Logger.Error($"保存用户,报错:{e.Message}\r\n{e.StackTrace}");
                response.Code    = ResponseCodeDefines.ServiceError;
                response.Message = e.Message;
                return(response);
            }
            return(response);
        }
예제 #23
0
        public async Task <ResponseMessage> Update(Models.UserInfo user, [FromBody] UpdatePeriodState updatePeriodState)
        {
            Logger.Trace($"用户{user?.UserName ?? ""}({user?.Id ?? ""})更改赛季信息,请求参数为:\r\n" + (updatePeriodState != null ? JsonHelper.ToJson(updatePeriodState) : ""));
            var response = new ResponseMessage();

            if (!ModelState.IsValid)
            {
                response.Code    = ResponseCodeDefines.ArgumentNullError;
                response.Message = "模型验证失败" + ModelState.GetAllErrors();
                Logger.Warn("添加赛季验证失败:\r\n{0}", response.Message ?? "");
            }
            if (user.IsAdmin == false)
            {
                response.Code    = ResponseCodeDefines.NotAllow;
                response.Message = "没有权限";
                Logger.Trace("没有权限:\r\n{0}", response.Message ?? "");
            }
            try
            {
                response = await _scorePeriodManager.UapdatePeriodState(updatePeriodState);
            }
            catch (Exception e)
            {
                response.Code    = ResponseCodeDefines.ServiceError;
                response.Message = e.Message;
                Logger.Error($"用户{user?.UserName ?? ""}({user?.Id ?? ""})更改赛季状态,报错:{e.Message}\r\n{e.StackTrace}");
            }
            return(response);
        }
예제 #24
0
        public async Task <ResponseMessage <List <PeriodReponse> > > SearchAllPeriod(Models.UserInfo user)
        {
            Logger.Trace($"用户{user?.UserName ?? ""}({user?.Id ?? ""})查询赛季列表");
            var response = new ResponseMessage <List <PeriodReponse> >();

            if (!ModelState.IsValid)
            {
                response.Code    = ResponseCodeDefines.ArgumentNullError;
                response.Message = "模型验证失败" + ModelState.GetAllErrors();
                Logger.Warn("查询赛季列表验证失败:\r\n{0}", response.Message ?? "");
                return(response);
            }
            if (user.IsAdmin == false)
            {
                response.Code    = ResponseCodeDefines.NotAllow;
                response.Message = "没有权限";
                Logger.Trace("没有权限:\r\n{0}", response.Message ?? "");
            }
            try
            {
                response = await _scorePeriodManager.SearchPeriodlist();
            }
            catch (Exception e)
            {
                response.Code    = ResponseCodeDefines.ServiceError;
                response.Message = e.Message;
                Logger.Error($"用户{user?.UserName ?? ""}({user?.Id ?? ""})查询赛季列表,报错:{e.Message}\r\n{e.StackTrace}");
            }
            return(response);
        }
예제 #25
0
        public async Task <HttpResponseMessage> AuthenticateUser([FromBody] Models.UserInfo userInfo)
        {
            try
            {
                var user = await _userDomainService.GetUserByNameAndPassword(userInfo.Name, userInfo.Password);

                if (user == null)
                {
                    return new HttpResponseMessage(HttpStatusCode.NotFound)
                           {
                               Content = new ObjectContent <UserDto>(user, new JsonMediaTypeFormatter(), "application/json")
                           }
                }
                ;
                else
                {
                    return(new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new ObjectContent <UserDto>(user, new JsonMediaTypeFormatter(), "application/json")
                    });
                }
            }
            catch (Exception ex)
            {
                return(new HttpResponseMessage(HttpStatusCode.InternalServerError));
            }
        }
예제 #26
0
        public async Task <ActionResult> Put([FromBody] Models.UserInfo value)
        {
            if (string.IsNullOrWhiteSpace(value.Password))
            {
                return(BadRequest("Invalid password."));
            }
            value.Role         = UserInfo.GetRole(value.Role);
            value.PasswordHash = PasswordStorage.CreateHash(value.Password);
            var res = await _context.UserInfos.FindAsync(value.UserName);

            if (res != null)
            {
                _context.Entry(res).CurrentValues.SetValues(value);
                await _context.SaveChangesAsync();

                return(Ok());
            }
            else
            {
                _context.UserInfos.Add(value);
                await _context.SaveChangesAsync();

                return(Ok());
            }
        }
예제 #27
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    int lastid;
                    var hasUser = (from row in db.UserInfos
                                   select row).FirstOrDefault();

                    if (hasUser != null)
                    {
                        lastid = (from row in db.UserInfos
                                  select row.Id).Max();
                    }

                    else
                    {
                        lastid = 0;
                    }

                    Models.UserInfo ui = new Models.UserInfo();
                    ui.Id           = lastid + 1;
                    ui.FullName     = model.FullName;
                    ui.Email        = model.Email;
                    ui.RegisterDate = DateTime.Now;

                    repository.InsertUserInfo(ui);

                    if (user.Email.ToLower() == "*****@*****.**".ToLower())
                    {
                        repository.InsertRole(user.Id, "100");
                    }
                    else
                    {
                        repository.InsertRole(user.Id, "200");
                    }

                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                    // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return(RedirectToAction("Index", "Home"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
예제 #28
0
 /// <summary>
 /// 保存用户信息
 /// </summary>
 /// <param name="user"></param>
 public void SaveUserInfo(Models.UserInfo user)
 {
     if (user == null)
     {
         return;
     }
     BinarySerializeHelper.Serialize(Paths.UserInfoFile, user);
 }
예제 #29
0
 public IActionResult GetToken([FromBody] Models.UserInfo user)
 {
     if (IsValidUserAndPassword(user.UserName, user.Password))
     {
         return(new ObjectResult(_tokenService.GenerateToken(user.UserName)));
     }
     return(Unauthorized());
 }
예제 #30
0
 public IHttpActionResult UserInfoUpdate(Models.UserInfo userInfo)
 {
     return(GetJsonResult(new Models.BaseResponse()
     {
         ResponseObject = new MiddelLayer.Users().Update(userInfo),
         Message = "Data update successfully.",
         StatusCode = 200
     }));
 }