public async Task <IActionResult> Edit(int id, [Bind("Id,NmName,DsEmail")] TbUser tbUser)
        {
            if (id != tbUser.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(tbUser);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TbUserExists(tbUser.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(tbUser));
        }
Beispiel #2
0
        private static IEnumerable <Claim> AllocateClaims(TbUser user)
        {
            var claims = new List <Claim>
            {
                new Claim(JwtClaimTypes.PreferredUserName, user.StrUserId),
                new Claim(JwtClaimTypes.Role, RoleNames.Player)
            };

            if (!string.IsNullOrEmpty(user.Name))
            {
                claims.Add(new Claim(JwtClaimTypes.Name, user.Name));
            }

            if (user.Gmrank.GetValueOrDefault() == 0)
            {
                return(claims);
            }

            claims.Add(new Claim(JwtClaimTypes.Role, RoleNames.GameMaster));

            if (!(user.SecPrimary == 1 && user.SecContent == 1))
            {
                return(claims);
            }

            claims.Add(new Claim(JwtClaimTypes.Role, RoleNames.GameDeveloper));

            return(claims);
        }
 public int CreateAccount(AccountModel model)
 {
     using (var db = new EntityContext())
     {
         if (!CheckExistingAccount(model.Username))
         {
             TbUser newUser = new TbUser
             {
                 isDelete    = false,
                 Username    = model.Username,
                 Password    = model.Password,
                 Phonenumber = model.Phonenumber,
                 Role        = db.tbRoles.FirstOrDefault(r => r.Role == model.Role),
                 Status      = db.tbStatuses.First(s => s.Status == model.Status)
             };
             db.tbUsers.Add(newUser);
             db.SaveChanges();
             return(newUser.Id);
         }
         else
         {
             return(0);
         }
     }
 }
Beispiel #4
0
        public ActionResult UploadAvatar(HttpPostedFileBase file) //HttpPostedFileBase là 1 thuộc tính của input giúp lấy được tên ảnh
        {
            string fileName = file.FileName;
            int    userId   = int.Parse(User.Identity.Name);
            TbUser user     = db.TbUsers.Find(userId);

            string strFolder = Server.MapPath("~/data/users/" + user.Id);



            if (System.IO.File.Exists(strFolder + @"\" + user.Avatar))
            {
                System.IO.File.Delete(strFolder + @"\" + user.Avatar);
            }



            if (!Directory.Exists(strFolder))
            {
                //Tạo thư mục ID
                Directory.CreateDirectory(strFolder);
            }
            //Thêm ảnh vô thư mục ID đó
            file.SaveAs(strFolder + @"\" + fileName);

            user.Avatar = fileName;
            db.SaveChanges();
            return(Content("/data/users/" + user.Id + "/" + fileName));
        }
Beispiel #5
0
        public void UpdatePersonalInfo(TbUser model)
        {
            authDc.Transaction <IAuthDbRecord>(() => {
                var user    = authDc.Table <TbUser>().Find(userId);
                var address = authDc.Table <TbUserAddress>().FirstOrDefault(x => x.UserId == userId);

                user.FirstName   = model.FirstName;
                user.LastName    = model.LastName;
                user.Nationality = model.Nationality;
                user.Birthday    = model.Birthday;
                user.UpdatedTime = DateTime.UtcNow;

                if (address == null)
                {
                    user.Address             = model.Address;
                    user.Address.UserId      = user.Id;
                    user.Address.UpdatedTime = DateTime.UtcNow;
                }
                else
                {
                    address.AddressLine1 = model.Address.AddressLine1;
                    address.AddressLine2 = model.Address.AddressLine2;
                    address.Country      = model.Address.Country;
                    address.County       = model.Address.County;
                    address.State        = model.Address.State;
                    address.City         = model.Address.City;
                    address.Zipcode      = model.Address.Zipcode;
                    address.UpdatedTime  = DateTime.UtcNow;
                }
            });
        }
Beispiel #6
0
        public ActionResult UploadAvatar(HttpPostedFileBase file)
        {
            string fileName = file.FileName;
            int    userId   = 3;
            TbUser user     = db.TbUsers.Find(userId);

            string strFolder = Server.MapPath("~/data/users/" + user.Id);



            if (System.IO.File.Exists(strFolder + @"\" + user.Avatar))
            {
                System.IO.File.Delete(strFolder + @"\" + user.Avatar);
            }



            if (!Directory.Exists(strFolder))
            {
                Directory.CreateDirectory(strFolder);
            }
            file.SaveAs(strFolder + @"\" + fileName);

            user.Avatar = fileName;
            db.SaveChanges();
            return(Content("/data/users/" + user.Id + "/" + fileName));
        }
        public ActionResult Register(TbUser user)
        {
            var emailUser = db.TbUsers.Where(x => x.Email == user.Email).SingleOrDefault();

            if (emailUser != null)
            {
                return(Json("This email already exists"));
            }

            if (user.Password == null)
            {
                return(Json("Your email is valid!"));
            }

            TbUser newUser = new TbUser()
            {
                FullName    = user.FullName,
                Email       = user.Email,
                Password    = MySecurity.EncryptPassword(user.Password),
                StatusId    = 1,
                CreatedDate = DateTime.Now,
                CountLogin  = 0
            };

            db.TbUsers.Add(newUser);
            db.SaveChanges();
            Authen(newUser.Id);

            //sendmail
            EmailManagement.SendMail(user.Email, "Aptech Shose Shop",
                                     "<h1>Hello [Name]! You have successfully registered an account at Aptech Shose Shop</h1>".Replace("[Name]", newUser.FullName));
            return(RedirectToAction("Index", "Home"));
        }
Beispiel #8
0
        public ActionResult _GetUserById(int UserID)
        {
            var tbUser = new TbUser();

            _IUser.EditUser(tbUser);
            return(View());
        }
Beispiel #9
0
        public async Task <IActionResult> LoginAsync(LoginModel model)
        {
            TbUser user = await rep.GetEntityAsync(s => s.Name.Equals(model.name));

            if (user == null)
            {
                return(NotFound($"用户名'{model.name}'不存在"));
            }
            if (!WxAppEncryptUtil.MD5(model.pwd).Equals(user.Pwd))
            {
                return(ValidationProblem(new ValidationProblemDetails()
                {
                    Detail = "密码错误"
                }));
            }

            string   token     = AuthorizationUtil.GetToken(30, user.Id, user.Name, "user", user.CarNum);
            DateTime authTime  = DateTime.Now;
            DateTime expiresAt = authTime.AddMinutes(30);

            return(Ok(new
            {
                access_token = token,
                token_type = Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerDefaults.AuthenticationScheme,
                profile = new
                {
                    sid = user.Id,
                    name = user.Name,
                    auth_time = new DateTimeOffset(authTime).ToUnixTimeSeconds(),
                    expires_at = new DateTimeOffset(expiresAt).ToUnixTimeSeconds()
                }
            }));
        }
Beispiel #10
0
        private void TbUser_TextChanged(object sender, EventArgs e)
        {
            string context  = TbUser.Text;
            bool   isletter = true;

            //for loop checks for letters as characters are entered
            for (int i = 0; i < context.Length; i++)
            {
                if (!char.IsLetter(context[i])) // if current character not a letter
                {
                    isletter = false;           //make isletter false
                    break;                      // exit the for loop
                }
            }

            // if not a letter clear the textbox and focus on it
            // to enter name again
            if (isletter == false)
            {
                TbUser.Clear();
                TbUser.Focus();
            }
            else
            {
                BtnStart.Enabled = true;
            }
        }
Beispiel #11
0
        public async Task <IActionResult> WxLoginAsync(WxLoginParam loginParam)
        {
            // 使用IHttpClientFactory创建的HttpClient
            OpenIdParam openIdParam = await WxUtils.GetOpenIdAsync(loginParam, clientFactory.CreateClient());

            if (openIdParam == null || string.IsNullOrEmpty(openIdParam.session_key))
            {
                return(ValidationProblem("验证错误,Secret可能失效"));
            }
            WxPhoneModel wxPhoneModel = WxAppEncryptUtil.GetEncryptedDataStr(loginParam.EncryptedData, openIdParam.session_key, loginParam.Iv);

            if (wxPhoneModel == null)
            {
                return(ValidationProblem("用户信息解析错误"));
            }
            string phone = wxPhoneModel.PurePhoneNumber ?? wxPhoneModel.PhoneNumber;

            if (string.IsNullOrEmpty(phone))
            {
                return(ValidationProblem("可能未绑定手机号"));
            }
            TbUser user = await rep.GetEntityAsync(s => s.Phone.Equals(phone), s => new TbUser {
                State = s.State
            });

            if (user == null)
            {
                return(ValidationProblem("用户未注册"));
            }
            string token = AuthorizationUtil.GetToken(30, user.Id, user.Name, "user", user.CarNum);

            return(Ok(new { access_token = token }));
        }
Beispiel #12
0
        public void EditUser(TbUser CurUser)
        {
            var User = GetAll().FirstOrDefault(x => x.Id == CurUser.Id);

            if (CurUser.FirstName != null)
            {
                User.FirstName = CurUser.FirstName;
            }
            if (CurUser.LastName != null)
            {
                User.LastName = CurUser.LastName;
            }
            if (CurUser.Status != null)
            {
                User.Status = CurUser.Status;
            }
            if (CurUser.UserType != null)
            {
                User.UserType = CurUser.UserType;
            }
            if (CurUser.AuthoriseLevel != null)
            {
                User.AuthoriseLevel = CurUser.AuthoriseLevel;
            }
            if (CurUser.Email != null)
            {
                User.Email = CurUser.Email;
            }
            if (CurUser.Password != null)
            {
                User.Password = CurUser.Password;
            }
            _context.SaveChanges();
        }
Beispiel #13
0
 public TbUserModel(TbUser tbUser)
 {
     UserId   = tbUser.UserId;
     Name     = tbUser.Name;
     Login    = tbUser.Login;
     Password = tbUser.Password;
 }
Beispiel #14
0
 protected void Page_Load(object sender, EventArgs e)
 {
     TbUser.Focus();
     // string CS = "data source=.; database = Sample; integrated security=SSPI";
     // SqlConnection con = new SqlConnection(CS);
     // SqlCommand cmd = new SqlCommand("Select * from ");
 }
        public TbTrazaEjecucionModel saveTrace(string tbTrazaEjecucionModel)
        {
            try
            {
                string           login          = string.Empty;
                TbTrazaEjecucion trazaEjecucion = JsonConvert.DeserializeObject <TbTrazaEjecucion>(tbTrazaEjecucionModel);
                if (trazaEjecucion != null)
                {
                    TbUser usr = db.TbUsers.Find(trazaEjecucion.UserId);
                    login = usr.Login;

                    trazaEjecucion.Date = DateTime.Now;
                    db.TbTrazaEjecucions.Add(trazaEjecucion);
                    db.SaveChanges();
                }
                else
                {
                    trazaEjecucion = new TbTrazaEjecucion();
                }

                TbTrazaEjecucionModel trazaEjecucionModel = new TbTrazaEjecucionModel(trazaEjecucion);
                trazaEjecucionModel.Login = login;

                return(trazaEjecucionModel);
            }
            catch (Exception ex)
            {
                TbTrazaEjecucionModel trazaEjecucionModel = new TbTrazaEjecucionModel();
                trazaEjecucionModel.TrazaEjecucionId = -1;
                trazaEjecucionModel.Observations     = ex.InnerException == null ? ex.Message : ex.InnerException.Message;
                return(trazaEjecucionModel);
            }
        }
    /// <summary>
    /// 新增和修改教师信息
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ButtonOK_Click(object sender, EventArgs e)
    {
        TbTeacher teacher = new TbTeacher();
        TbUser    user    = new TbUser();

        user.Zt        = int.Parse(userrole.SelectedValue);
        user.Xh        = "";
        teacher.LsName = teachername.Text.Trim();
        user.YhName    = teacheruser.Text.Trim();                                                                            //用户名(账号)
        user.YhPwd     = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(teacherpwd.Text, "MD5"); //密码
        teacher.ZyID   = int.Parse(this.teacherzy.SelectedValue);                                                            //专业
        teacher.Remark = textRemark.Text.Trim();
        if (this.hidTeacherID.Value != "")                                                                                   /*用户编号不为空,即为修改时*/
        {
            teacher.YhID = int.Parse(this.hidTeacherID.Value);
            user.YhID    = teacher.YhID;
            TbUserManager.UpdateUserRoleByYhID(user);
            TbTeacherManager.UpdateTeacherInfoByYhID(teacher);
            this.hidTeacherID.Value = "";
        }
        else
        {
            int yhid = TbUserManager.InsertTeacherUser(user.YhName, user.Xh, user.YhPwd, user.Zt);/*新增教师用户信息,返回其用户编号*/
            if (yhid > 0)
            {
                int Result = TbTeacherManager.InsertTeacherInfo(yhid, teacher.LsName, teacher.ZyID, teacher.Remark);
            }
        }
        teacherzy.Items.Clear();
        GetSpeciality();
        GetPageInfo();
        teachername.Text = "";
        teacherpwd.Text  = "";
        teacheruser.Text = "";
    }
Beispiel #17
0
        private AuthenticateResult GetToken(TbUser user)
        {
            //generate token
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[] {
                    new Claim(ClaimTypes.NameIdentifier, user.CdUser.ToString()),
                    new Claim(ClaimTypes.Name, user.DsEmail)
                }),
                Expires            = DateTime.Now.AddDays(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha512Signature)
            };

            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);

            return(new AuthenticateResult(
                       new AuthenticateResponse
            {
                Token = tokenString,
                ExpirationTime = DateTime.UtcNow.AddDays(7)
            }));
        }
Beispiel #18
0
        public ActionResult Register(TbUser user)
        {
            var emailUser = db.TbUsers.Where(x => x.Email == user.Email).SingleOrDefault();

            if (emailUser != null)
            {
                ModelState.AddModelError("", "Email này đã tồn tại");
                return(View());
            }

            TbUser newUser = new TbUser()
            {
                FullName    = user.FullName,
                Email       = user.Email,
                Password    = MySecurity.EncryptPassword(user.Password),
                StatusId    = 1,
                CreatedDate = DateTime.Now
            };

            db.TbUsers.Add(newUser);
            db.SaveChanges();
            Authen(newUser.Id);


            //sendmail
            EmailManagement.SendMail(user.Email, "Chuc mung dang ky thanh cong", "<h1>Hello [Name], ban da dag ky</h1>".Replace("[Name]", newUser.FullName));
            return(RedirectToAction("Index", "Home"));
            ///return Redirect(Request.UrlReferrer.ToString());
        }
Beispiel #19
0
        public string Post([FromBody] TbUser value)
        {
            if (!dbXamarinContext.TbUsers.Any(User => User.Username.Equals(value.Username)))
            {
                TbUser user = new TbUser();
                user.Username = value.Username;
                user.Salt     = Convert.ToBase64String(Common.GetRandomSalt(16));
                user.Password = Convert.ToBase64String(Common.SaltHashPassword(
                                                           Encoding.ASCII.GetBytes(value.Password),
                                                           Convert.FromBase64String(user.Salt)));

                try
                {
                    dbXamarinContext.Add(user);
                    dbXamarinContext.SaveChanges();
                    return(JsonConvert.SerializeObject("Register Successfully"));
                }
                catch (Exception ex)
                {
                    return(JsonConvert.SerializeObject(ex.Message));
                }
            }
            else
            {
                return(JsonConvert.SerializeObject("User is Existing in Database"));
            }
        }
Beispiel #20
0
        public IHttpActionResult PutTbUser(int id, TbUser tbUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != tbUser.usr_id)
            {
                return(BadRequest());
            }

            db.Entry(tbUser).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TbUserExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
        public ActionResult DeleteConfirmed(int id)
        {
            TbUser tbUser = db.TbUsers.Find(id);

            db.TbUsers.Remove(tbUser);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Beispiel #22
0
    /// <summary>
    /// 根据用户ID查询对应详细信息
    /// </summary>
    /// <param name="YhID"></param>
    public void GetStudent(int YhID)
    {
        TbStudent student = TbStudentManager.GetStudentByID(YhID);
        TbUser    user    = TbUserManager.GetAllUser(YhID);
        string    message = student.YhID + "," + student.XsName + "," + student.XsSex + "," + student.BjName + "," + student.Remark + "," + user.YhName + "," + user.Xh + "," + user.YhPwd;

        Response.Write(message);
    }
Beispiel #23
0
 public JsonResult Register([FromForm] TbUser user, [FromForm] string code)
 {
     _userService.Register(user, code);
     return(new JsonResult(new AjaxResult()
     {
         Result = true,
         Message = "注册成功"
     }));
 }
Beispiel #24
0
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            TbUser tbUser = await db.TbUsers.FindAsync(id);

            db.TbUsers.Remove(tbUser);
            await db.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
Beispiel #25
0
        public void DeleteUser(int id)
        {
            var User = new TbUser {
                Id = id
            };

            _context.TableUser.Remove(User);
            _context.SaveChanges();
        }
Beispiel #26
0
        public TbUserModel saveUser(string tbUserModel, string tbModuleModels)
        {
            try{
                TbUser user = JsonConvert.DeserializeObject <TbUser>(tbUserModel);
                if (user != null)
                {
                    if (user.UserId == 0)
                    {
                        db.TbUsers.Add(user);
                        db.SaveChanges();
                    }
                    else
                    {
                        TbUser userEdit = db.TbUsers.Find(user.UserId);
                        if (userEdit != null && userEdit.UserId > 0)
                        {
                            userEdit.Name     = user.Name;
                            userEdit.Login    = user.Login;
                            userEdit.Password = user.Password;

                            db.Entry(userEdit).State = EntityState.Modified;

                            List <TnUserAuthorization> tnUserAuthorizationLst = db.TnUserAuthorizations.Where(t => t.User == user.UserId).ToList();
                            db.TnUserAuthorizations.RemoveRange(tnUserAuthorizationLst);
                        }
                    }

                    List <TbModuleModel> tbModuleList = JsonConvert.DeserializeObject <List <TbModuleModel> >(tbModuleModels);
                    foreach (TbModuleModel tbModu in tbModuleList)
                    {
                        if (tbModu.IsSelected)
                        {
                            TnUserAuthorization autor = new TnUserAuthorization();
                            autor.User   = user.UserId;
                            autor.Module = tbModu.ModuleId;
                            db.TnUserAuthorizations.Add(autor);
                        }
                    }

                    db.SaveChanges();
                }
                else
                {
                    user = new TbUser();
                }

                TbUserModel usrModel = new TbUserModel(user);
                return(usrModel);
            }
            catch (Exception ex)
            {
                TbUserModel usrModel = new TbUserModel();
                usrModel.UserId = -1;
                usrModel.Name   = ex.InnerException == null ? ex.Message : ex.InnerException.Message;
                return(usrModel);
            }
        }
Beispiel #27
0
        /// <summary>
        /// 根据用户编号修改教师用户的角色
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public int UpdateUserRoleByYhID(TbUser user)
        {
            string sql = "update tbUser set Zt=@zt where YhID=@yhid";

            SqlParameter[] paras = new SqlParameter[] {
                new SqlParameter("@zt", user.Zt),
                new SqlParameter("@yhid", user.YhID)
            };
            return(DBHelper.ExecuteCommand(sql, paras));
        }
Beispiel #28
0
        /// <summary>
        /// 根据相应信息查找对应用户是否存在
        /// </summary>
        /// <param name="user">用户对象</param>
        /// <returns>返回对应用户的个数</returns>
        public int SeeUser(TbUser user)
        {
            string Sql_Select = "select count(*) from tbUser where YhName=@YhName or Xh=@Xh";

            SqlParameter[] paras = new SqlParameter[] {
                new SqlParameter("@YhName", user.YhName),
                new SqlParameter("@Xh", user.Xh)
            };
            return(DBHelper.GetScalar(Sql_Select, paras));
        }
Beispiel #29
0
 public ActionResult Index()
 {
     if (User.Identity.IsAuthenticated)
     {
         int    userId = int.Parse(User.Identity.Name);
         TbUser u      = db.TbUsers.Find(userId);
         ViewBag.Name = u.FullName;
     }
     return(View());
 }
 public ActionResult Edit([Bind(Include = "Id,FullName,Gender,Email,Address,Password,StatusId,CreatedDate,Avatar")] TbUser tbUser)
 {
     if (ModelState.IsValid)
     {
         db.Entry(tbUser).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.StatusId = new SelectList(db.StatusUsers, "Id", "StatusName", tbUser.StatusId);
     return(View(tbUser));
 }
Beispiel #31
0
        /// <summary>
        /// Adds a user to the system asyncronously
        /// </summary>
        /// <param name="userModel">User's data</param>
        /// <returns>Task to enable asynchronous execution</returns>
        public async Task AddUserAsync(TbUserRoleVm userModel)
        {
            // Base user constructor creates Id, which must be kept in the model before mapping
            var user = new TbUser();
            userModel.UserId = user.Id;

            // Execute mapping from the view model to the domain object
            user = _mapper.Map<TbUserRoleVm, TbUser>(userModel, user);

            // TODO: consider more secure psw generation 
            string password = "******";

            // Envelop the sequence of the db operations in the transaction scope
            using(var transaction = TransactionProvider.GetTransactionScope())
            {
                // Create a user
                var result = UserManager.Create(user, password);
                if(result == null || !result.Succeeded)
                {
                    throw new TbIdentityException("Create user error", result);
                }

                // Add a user to the specified role
                string role = userModel.Role;
                long projectId = (long)userModel.ProjectId;
                string userId = user.Id;

                result = UserManager.AddToRole(userId, role);
                if(result == null || !result.Succeeded)
                {
                    throw new TbIdentityException("Add to role error", result);
                }

                // Add a user to the specified project
                var projectUsers = new ProjectUsers()
                {
                    ProjectId = projectId,
                    UserId = userId
                };

                var projectUsersRepository = _unitOfWork.ProjectUsersRepository;
                projectUsersRepository.Add(projectUsers);

                // If just added user is a manager, delete "NotAssigned" (manager) system account from the project
                if(role == RoleKey.Manager)
                {
                    string notAssignedUserId = UserManager.FindByName("NotAssigned").Id;
                    projectUsersRepository.DeleteByPredicate(x => x.UserId == notAssignedUserId && x.ProjectId == projectId);
                }
                _unitOfWork.Commit();
                transaction.Complete();
            }

            // Create email notification and send it
            string login = string.Format("{0}/#/login", Host);
            string retrive = string.Format("{0}/#/forgotPassword", Host);
            string body = string.Format(_addUserEmailBodyConst, user.FirstName, user.UserName, password, retrive, login);
            MailMessage message = new MailMessage();
            message.To.Add(user.Email);
            message.Subject = "Add account";
            message.Body = body;

            await _emailService.SendMailAsync(message);
        }