public IActionResult Register(RegisterModel model) { try { var user = _db.TblUser.Any(x => x.Email.Equals(model.Email)); if (!user) { TblUser tblUser = new TblUser() { Email = model.Email, FirstName = model.FirstName, Password = model.Password, LastName = model.LastName }; _db.TblUser.Add(tblUser); _db.SaveChanges(); ModelState.Clear(); ViewBag.Class = "alert-success"; ViewBag.Message = "Registered successfully"; } else { ViewBag.Class = "alert-danger"; ViewBag.Message = "Email already exists"; } return(View()); } catch (Exception ex) { ViewBag.Class = "alert-danger"; ViewBag.Message = ex.Message; return(View()); } }
public ActionResult GetActivities(string selectedType) { TblUser sessionUser = (TblUser)Session["UserSession"]; List <Param> activityList = new List <Param>(); try { if (selectedType == "1") { activityList = cc.GetCurriculumCourses(sessionUser.TenantId); } if (selectedType == "2") { activityList = cc.GetCurriculumSurveys(sessionUser.TenantId); } if (selectedType == "3") { activityList = cc.GetCurriculumForums(sessionUser.TenantId); } } catch (Exception ex) { newException.AddException(ex); } return(Json(activityList, JsonRequestBehavior.AllowGet)); }
public async Task <IActionResult> Edit(int id, [Bind("UserId,UserFname,UserLname,UserDob,UserGender,UserCityId,UserPassword,UserMobile,UserEmail,CreateDate,UpdateDate,IsActive,IsDelete")] TblUser tblUser) { if (id != tblUser.UserId) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(tblUser); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TblUserExists(tblUser.UserId)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["UserCityId"] = new SelectList(_context.TblCity, "CityId", "CityId", tblUser.UserCityId); return(View(tblUser)); }
/// <summary> /// UpdateUserById - sửa thông tin user /// </summary> /// <param name="emp"></param> /// <returns></returns> public bool UserEditProfile(TblUser tblUser) { SqlParameter[] paramList = new SqlParameter[7]; paramList[0] = new SqlParameter("@UserName", SqlDbType.VarChar, 256); paramList[0].Value = tblUser.UserName; paramList[1] = new SqlParameter("@FullName", SqlDbType.NVarChar, 256); paramList[1].Value = tblUser.FullName; paramList[2] = new SqlParameter("@DateOfBirth", SqlDbType.DateTime); paramList[2].Value = tblUser.DateOfBirth; paramList[3] = new SqlParameter("@Gender", SqlDbType.Bit); paramList[3].Value = tblUser.Gender; paramList[4] = new SqlParameter("@Email", SqlDbType.NVarChar, 256); paramList[4].Value = tblUser.Email; paramList[5] = new SqlParameter("@Address", SqlDbType.NVarChar, 256); paramList[5].Value = tblUser.Address; paramList[6] = new SqlParameter("@Phone", SqlDbType.VarChar, 50); paramList[6].Value = tblUser.Phone; if (db.executeUpdate("EditProfile", paramList) == 0) { return(false); } else { return(true); } }
public async Task <IActionResult> Edit(decimal id, [Bind("UserId,Username,Password,Lock,RoleId,CreatedBy,CreatedDate")] TblUser tblUser) { if (id != tblUser.UserId) { return(NotFound()); } if (ModelState.IsValid) { try { db.Update(tblUser); await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TblUserExists(tblUser.UserId)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(tblUser)); }
public IActionResult UserProfile(UserViewModel model) { string unqiueFileName = string.Empty; if (model.ProfileImage != null) { if (model.ProfileImage.FileName != null) { unqiueFileName = UploadedFile(model); if (model.profilePic != null) { System.IO.File.Delete(Path.Combine(_webHostEnvironment.WebRootPath, "App_Shared/" + model.profilePic)); } } } model.lstCity = _account.getCities(); model.lstGender = _lookUp.GetGender(); model.lstCountry = Common.GetCountry(); model.lstFamilyStatus = _lookUp.GetFamilyStatus(); model.profilePic = unqiueFileName; TblUser user = _account.updateUser(model); if (user != null) { TempData["Message"] = Constants.UpdateUserProfile; } return(RedirectToAction("UserProfile")); }
public IGernalResult UserRegistration(UserDto dto) { IGernalResult result = new GernalResult(); try { TblUser User = new TblUser { Name = dto.Name, Address = dto.Address, Email = dto.Email, Password = dto.Password, ImageUrl = dto.ImageUrl, RoleId = dto.RoleId, MobileNo = dto.MobileNo, CreatedDate = DateTime.UtcNow, IsSeller = dto.RoleId > 1 ? true : false }; string userType = dto.RoleId > 1 ? "Seller" : "User"; _dbContext.Add(User); int save = _dbContext.SaveChanges(); result.Succsefully = save > 0 ? true : false; result.Message = save > 0 ? userType + " register Succsefully" : userType + "not register"; } catch { result.Succsefully = false; result.Message = "server error"; } return(result); }
public int Update(UserModel entity) { TblUser obj = _mapper.Map <UserModel, TblUser>(entity); _repository.Update(obj); return(obj.UserId); }
public TblUser saveSignUp(UserViewModel user) { TblUser oldUser = _context.TblUser.Where(i => i.Id == user.Id).FirstOrDefault(); if (oldUser != null) { if (!string.IsNullOrEmpty(user.password)) { oldUser.Password = Common.EncryptPassword(user.password); } oldUser.MaritalStatus = Convert.ToInt32(user.maritalStatus); oldUser.FullName = user.surname; oldUser.Gender = user.gender; oldUser.Age = user.age; oldUser.Country = user.country; oldUser.City = Convert.ToInt64(user.city); oldUser.Role = UserRole.User; oldUser.Status = InvitationStatuses.Approved; if (!string.IsNullOrEmpty(user.profilePic)) { oldUser.ProfilePicture = user.profilePic; } _context.SaveChanges(); } return(oldUser); }
public IGernalResult EditUser(UserDto dto) { IGernalResult result = new GernalResult(); try { TblUser User = _dbContext.TblUser.Where(w => w.Id == dto.Id).FirstOrDefault(); { User.Name = dto.Name; User.Address = dto.Address; User.ImageUrl = dto.ImageUrl; }; int save = _dbContext.SaveChanges(); result.Succsefully = save > 0 ? true : false; result.Message = save > 0 ? "User update Succsefully" : "User not update"; } catch { result.Succsefully = false; result.Message = "server error"; } return(result); }
public async Task <IActionResult> Login([Bind("UserName,Password")] TblUser tblUser) { if (ModelState.IsValid) { var user = await _userRepository.GetLoginInfo(tblUser.UserName, tblUser.Password); if (user == null) { TempData["message"] = "Invalid credential"; return(View(tblUser)); } Guid guid = Guid.NewGuid(); string token = guid.ToString(); CurrentUser.Users.Add(token, user); HttpContext.Session.SetString("token", token); ViewBag.loggedInUserName = CurrentUser.Users[token].UserName; ViewBag.loggedInUserId = CurrentUser.Users[token].UserId; TempData["message"] = "Hello, " + CurrentUser.Users[token].UserName; return(RedirectToAction("Index", "Movie")); } return(View(tblUser)); }
public async Task <IActionResult> Edit(Guid id, [Bind("UserId,FirstName,LastName,Email,UserName,Password")] TblUser tblUser) { if (id != tblUser.UserId) { return(NotFound()); } if (ModelState.IsValid) { try { await _userRepository.Update(tblUser); } catch (DbUpdateConcurrencyException) { if (!TblUserExists(tblUser.UserId)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(tblUser)); }
public static UserObj MagicMapper(this TblUser item) { if (item == null) { return(null); } //List<RoleObj> listRoles; //foreach (var x in item.TblRoles) //{ // listRoles.Add //} UserObj obj = new UserObj { UserId = item.UserId, Firstname = item.Firstname, Lastname = item.Lastname, Phone = item.Phone, Fax = item.Fax, Username = item.Username, EmailSmtp = item.EmailSmtp, Active = item.Active }; //obj.TblRoles = item.TblRoles. return(obj); }
public async Task <ActionResult> Edit([Bind(Exclude = "UserId,Name,Hash,Salt,UserType,Password")] TblUser tblUser) { var email = from data in db.TblUsers where data.Email.Equals(tblUser.Email) select data.Email; var sysData = from data in db.TblSysCredentials select data; if (Session["UserId"] == null && email.FirstOrDefault() != null) { Email.Email.BuildEmailTemplate(email.FirstOrDefault(), sysData.FirstOrDefault().Email, sysData.FirstOrDefault().Password); ViewBag.SendEmail = "EmailSent"; return(RedirectToAction("ForgetPassword")); } else { List <string> encryptedPasswordAndSalt = Password.Ecrypt(tblUser.Password); TblUser user = (from x in db.TblUsers where x.Email == tblUser.Email select x).FirstOrDefault(); if (user.UserId == Convert.ToInt32(Session["UserId"])) { user.Salt = encryptedPasswordAndSalt[0]; user.Hash = encryptedPasswordAndSalt[1]; await db.SaveChangesAsync(); Session["UserId"] = null; return(RedirectToAction("Index", "Home")); } else { //Email and userId not matched //Entered wrong or some other user's email return(Content("<script language='javascript' type='text/javascript'>alert('Email does not match with registered email!')</script >")); } } }
public IActionResult ChangePassword(ChangePassword change) { if (string.IsNullOrEmpty(change.CurrentPassword) || string.IsNullOrEmpty(change.NewPassword) || string.IsNullOrEmpty(change.ConfirmPassword)) { return(BadRequest(new { message = "Password is empty" })); } if (change.NewPassword.Equals(change.ConfirmPassword)) { return(BadRequest(new { message = "Password is empty" })); } var value = _context.TblUser.ToList().Any(a => a.Password.Equals(change.CurrentPassword)); if (value == true) { var userId = _context.TblUser.Where(a => a.Password.Equals(change.CurrentPassword)).First().UserId; TblUser user = _context.TblUser.Find(userId); user.Username = user.Username; user.Password = change.NewPassword; user.Lock = user.Lock; user.RoleId = user.RoleId; user.Mobile = user.Mobile; user.BetLimitForMix = user.BetLimitForMix; user.BetLimitForSingle = user.BetLimitForSingle; user.SharePercent = user.SharePercent; user.CreatedBy = user.CreatedBy; user.CreatedDate = user.CreatedDate; _context.SaveChanges(); return(Ok(new { Message = "Successfully Changed" })); } return(BadRequest(new { Message = "Password is incorrect" })); }
public ActionResult Login(TblUser model) { if (ModelState.IsValid) { var user = (from userlist in db.User_tbl where userlist.EmailId == model.EmailId && userlist.Password == model.Password select new { userlist.UserId, userlist.EmailId }).ToList(); if (user.FirstOrDefault() != null) { Session["EmailId"] = user.FirstOrDefault().EmailId; Session["UserId"] = user.FirstOrDefault().UserId; return(RedirectToAction("LoginMain", "Account")); } else { return(Content("<script type='text/javascript'>window.alert('Invalid login');window.location.href='';</script>")); // return RedirectToAction("Login", "Account"); } } return(View()); }
public ActionResult LoginIndex(TblUser TblUser, TblHistoryLogin tblhistorylogin) { string pass = EncryptandDecrypt.Encrypt(TblUser.Password); var list = db.TblUser.Where(p => p.UserName == TblUser.UserName && p.Password == pass && p.Active == true).ToList(); if (list.Count > 0) { var userCookie = new HttpCookie("Username"); var id = list[0].Id.ToString(CultureInfo.InvariantCulture); var username = list[0].UserName; var fullname = list[0].FullName; userCookie.Values["UserID"] = id; userCookie.Values["FullName"] = Server.HtmlEncode(fullname.Trim()); userCookie.Values["fullname"] = fullname; userCookie.Values["UserName"] = Server.UrlEncode(username.Trim()); userCookie.Values["username"] = username; tblhistorylogin.FullName = fullname; tblhistorylogin.Task = "Login hệ thống"; tblhistorylogin.IdUser = int.Parse(id); tblhistorylogin.DateCreate = DateTime.Now; tblhistorylogin.Active = true; db.TblHistoryLogin.Add(tblhistorylogin); db.SaveChanges(); userCookie.Expires = DateTime.Now.AddHours(22); Response.Cookies.Add(userCookie); Session["Count"] = ""; return(Redirect("/Productad/Index")); } else { ViewBag.Note = "Tài khoản của bạn nhập không đúng, kiểm tra lại tên đăng nhập hoặc mật khẩu. Có thể tài khoản bị khóa !"; return(View()); } }
protected TblProfesor GetDatosVista(TblProfesor prof) { TblDireccion direccion = new TblDireccion(); direccion.strestado = txtDirecEstado.Text.ToUpper(); direccion.strmunicipio = txtDirecMunicipio.Text.ToUpper(); direccion.strcolonia = txtDirecColonia.Text.ToUpper(); direccion.strcalle = txtDirecCalle.Text.ToUpper(); direccion.intcodpost = Int32.Parse(txtIntCodigo.Text); direccion.strnumInt = txtDirecInter.Text.ToUpper(); direccion.strnumExt = txtDirecExt.Text.ToUpper(); direccion.strreferencias = txtDirecReferencia.Text.ToUpper(); TblTelefono telefono = new TblTelefono(); telefono.strcelular = txtTelCelular.Text.ToUpper(); telefono.strtelCasa = txtTelCasa.Text.ToUpper(); telefono.strotro = txtTelOtro.Text.ToUpper(); TblUser login = new TblUser(); login.strusuario = txtUsuario.Text.ToString(); login.strpass = txtPass.Text.ToString(); login.strtipoUsuario = "PROFESOR"; prof.TblDireccion = direccion; prof.TblTelefono = telefono; prof.TblUser = login; return(prof); }
public async Task <IActionResult> PutTblUser(string id, TblUser tblUser) { if (id != tblUser.UserName) { return(BadRequest()); } _context.Entry(tblUser).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TblUserExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public IActionResult UserProfile() { if (HttpContext.Session.GetString("userID") != null) { Int64? userId = Convert.ToInt64(Common.Decryption(HttpContext.Session.GetString("userID"))); TblUser user = _account.getUserByID(userId); UserViewModel model = new UserViewModel(); model.lstCity = _account.getCities(); model.lstGender = _lookUp.GetGender(); model.lstCountry = Common.GetCountry(); model.lstFamilyStatus = _lookUp.GetFamilyStatus(); if (user != null) { model.userName = user.Username; model.email = user.Username; model.Id = user.Id; model.password = user.Password; model.surname = user.FullName; model.maritalStatus = Convert.ToString(user.MaritalStatus); model.gender = user.Gender; model.age = user.Age; model.country = user.Country; model.city = Convert.ToString(user.City); model.profilePic = user.ProfilePicture; } return(View(model)); } else { return(RedirectToAction("Login", "Account")); } }
public async Task <ActionResult <UserWithToken> > RegisterUser([FromBody] TblUser user) { user.Password = _crypto.GenerateSaltedHash(Encoding.ASCII.GetBytes(user.Password), Encoding.ASCII.GetBytes(_salt)); _context.TblUsers.Add(user); await _context.SaveChangesAsync(); //load role for registered user user = await _context.TblUsers.Include(u => u.Role) .Where(u => u.Id == user.Id).FirstOrDefaultAsync(); UserWithToken userWithToken = null; if (user != null) { TblRefreshToken refreshToken = GenerateRefreshToken(); user.TblRefreshTokens.Add(refreshToken); await _context.SaveChangesAsync(); userWithToken = new UserWithToken(user); userWithToken.RefreshToken = refreshToken.Token; } if (userWithToken == null) { return(NotFound()); } //sign your token here here.. userWithToken.AccessToken = GenerateAccessToken(user.Id); return(userWithToken); }
public static void ExtUpdate(this TblUser value, UserModel obj) { value.IdRole = obj.IdRole; value.Login = obj.Login; value.Password = obj.Password; value.Name = obj.Name; }
public async Task <ActionResult <UserWithToken> > Login([FromBody] TblUser user) { user = await _context.TblUsers.Include(u => u.Role) .Where(u => u.Login == user.Login && u.Password == user.Password).FirstOrDefaultAsync(); UserWithToken userWithToken = null; if (user != null) { TblRefreshToken refreshToken = GenerateRefreshToken(); user.TblRefreshTokens.Add(refreshToken); await _context.SaveChangesAsync(); userWithToken = new UserWithToken(user); userWithToken.RefreshToken = refreshToken.Token; } if (userWithToken == null) { return(NotFound()); } //sign your token here here.. userWithToken.AccessToken = GenerateAccessToken(user.Id); return(userWithToken); }
public IActionResult login([FromBody] TblUser user, string password) { var jestUser = _ctx.TblUser.FirstOrDefault(x => x.FullName == user.FullName); if (jestUser == null) { return(Unauthorized()); } if (!VerifyPasswordHash(password, jestUser.PasswordHash, jestUser.PasswordSalt)) { return(Unauthorized()); } // tworzymy token JWT var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("superSecretKey@345")); var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256); var claims = new List <Claim> { new Claim(ClaimTypes.Name, jestUser.FullName), new Claim(ClaimTypes.Role, jestUser.position) }; var tokeOptions = new JwtSecurityToken( issuer: "http://localhost:5000", audience: "http://localhost:5000", claims: claims, expires: DateTime.Now.AddMinutes(15), signingCredentials: signinCredentials ); var tokenString = new JwtSecurityTokenHandler().WriteToken(tokeOptions); return(Ok(new { Token = tokenString, username = jestUser.FullName, position = jestUser.position })); }
public TblUser UpdateTblUserToDataBase(int UserID, TblUser uUser) { try { var dbUser = this.Context.TblUser.Find(UserID); if (dbUser != null) { uUser.CreateDate = dbUser.CreateDate; uUser.ModifyDate = this.DateOfServer; uUser.Modifyer = uUser.Modifyer ?? "someone"; if (string.IsNullOrEmpty(uUser.Password)) { uUser.Password = dbUser.Password; } this.Context.Entry(dbUser).CurrentValues.SetValues(uUser); return(this.Context.SaveChanges() > 0 ? this.GetTblUserWithKey(UserID) : null); } } catch (Exception ex) { Debug.WriteLine("Has error " + ex.ToString()); } return(null); }
public LoginPageViewModel() { if (Device.RuntimePlatform == Device.Android) { myAPI = RestService.For <IMyAPI>("http://10.0.2.2:5000"); } else if ((Device.RuntimePlatform == Device.UWP)) { myAPI = RestService.For <IMyAPI>("http://localhost:5000"); } else if ((Device.RuntimePlatform == Device.iOS)) { myAPI = RestService.For <IMyAPI>("http://127.0.0.1:5000"); } else { MessagingCenter.Send <LoginPageViewModel, string>(this, "Login", "Unsupported Device"); } user = new TblUser(); LoginCommand = new Command(async() => { try { var result = await myAPI.LoginUser(user); MessagingCenter.Send <LoginPageViewModel, string>(this, "Login", "Login Success"); } catch (Exception ex) { MessagingCenter.Send <LoginPageViewModel, string>(this, "Login", ex.Message); } }); }
public string Post([FromBody] TblUser value) { if (!dbContext.TblUser.Any(user => user.clmnUser.Equals(value.clmnUser))) { TblUser user = new TblUser(); user.clmnUser = value.clmnUser; user.clmnSalt = Convert.ToBase64String(Common.GetRandomSalt(16)); //get random Salt user.clmnPassword = Convert.ToBase64String(Common.SaltHashPassword( Encoding.ASCII.GetBytes(value.clmnPassword), Convert.FromBase64String(user.clmnSalt))); //Add to DB try { dbContext.Add(user); dbContext.SaveChanges(); return(JsonConvert.SerializeObject("Register successfully")); } catch (Exception ex) { return(JsonConvert.SerializeObject(ex.Message)); } } else { return(JsonConvert.SerializeObject("User is existing in Database")); } }
public ActionResult AddCurriculumToDB(string jsonData, string title, string CId) { try { TblUser sessionUser = (TblUser)Session["UserSession"]; tblCurriculum objCurriculum = new tblCurriculum(); objCurriculum.CreatedBy = sessionUser.UserId; objCurriculum.TenantId = sessionUser.TenantId; objCurriculum.CurriculumTitle = title; if (Convert.ToInt32(CId) > 0) { objCurriculum.CurriculumId = Convert.ToInt32(CId); } JavaScriptSerializer json_serializer = new JavaScriptSerializer(); json_serializer.MaxJsonLength = int.MaxValue; object[] objData = null; if (!string.IsNullOrEmpty(jsonData)) { objData = (object[])json_serializer.DeserializeObject(jsonData); } var result = cc.AddCurriculumToDB(objData, objCurriculum); } catch (Exception ex) { newException.AddException(ex); } return(Json("OK", JsonRequestBehavior.AllowGet)); }
public IHttpActionResult PutTblUser(int id, TblUser tblUser) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != tblUser.Id) { return(BadRequest()); } db.Entry(tblUser).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!TblUserExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public int IsUserExist(string email, string DomainName) { int userid = 0; try { db.parameters.Clear(); common = new Commonfunctions(); TblUser tblUser = new TblUser(); DataSet ds = new DataSet(); db = new DataRepository(); db.AddParameter("@emailId", SqlDbType.NVarChar, email); db.AddParameter("@domainName", SqlDbType.NVarChar, DomainName); ds = db.FillData("sp_PlekCheckUserExist"); if (ds != null) { if (ds.Tables.Count > 0) { if (ds.Tables[0].Rows.Count > 0) { userid = Convert.ToInt32(ds.Tables[0].Rows[0][0]); } } } return(userid); } catch (Exception ex) { newException.AddException(ex); return(userid); } }
public void Update(TblUser user) { using (_db = new ProvaNetEntities()) { _db.Configuration.ProxyCreationEnabled = false; _db.Entry(user).State = EntityState.Modified; _db.SaveChanges(); } }
public TblUser ValidarLogin(TblUser user) { TblUser response = null; using (_db = new ProvaNetEntities()) { _db.Configuration.ProxyCreationEnabled = false; string senhaCrypt = new Crypt().Password(user.Senha); response = _db.TblUser.FirstOrDefault( x => x.Email.Equals(user.Email) && x.Senha.Equals(senhaCrypt)); } return response; }