public CandidateInfoForManager GetCandidateFilesInfo(int candidateId) { var tokenString = Request.Headers["Authorization"]; var token = new TokenData(tokenString); if (!AuthManager.ValidateAuthToken(token)) { Response.StatusCode = (int)HttpStatusCode.NetworkAuthenticationRequired; return(null); } if (!UsersManager.GetUser(token).HasRoot(RootEnum.Manager)) { Response.StatusCode = (int)HttpStatusCode.Forbidden; return(null); } try { //Read Stream and convert to String AbstractUser user = AuthManager.Instance[token]; CandidateInfoForManager info = new CandidateInfoForManager(); info.userProfile = user.Profile; info.filesInfo = FileManager.GetFilesData(candidateId).Select(n => n.Data).ToArray(); return(info); } catch (FileException) { Response.StatusCode = (int)HttpStatusCode.NotFound; return(null); } }
public async Task <IActionResult> Login(LoginViewModel model) { if (ModelState.IsValid) { AbstractUser user = _abstractUserService.GetUserByEmail(model.Email); if (await _userManager.IsInRoleAsync(user, "Client")) { var result = await _signInManager.PasswordSignInAsync(user, model.Password, true, false); if (result.Succeeded) { return(RedirectToAction("Index", "Home")); } ModelState.AddModelError(string.Empty, "Your password or email does not match"); } else if (await _userManager.IsInRoleAsync(user, "Cook")) { var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, false); if (result.Succeeded) { ModelState.AddModelError(string.Empty, "You are not authorized to visit this website, please register as a new customer!"); } } } return(View(model)); }
public ActionResult Join(NewJoining newJoining) { if (newJoining.OrderID != 0) { string id = User.Identity.GetUserId(); AbstractUser user = db.AllUsers.OfType <AuthorizedUser>().Where(x => x.AppUser.Id == id).FirstOrDefault(); if (user == null) { user = new UnauthorizedUser(); user.FirstName = newJoining.UserFirstName; user.LastName = newJoining.UserLastName; db.AllUsers.Add(user); db.SaveChanges(); } if (newJoining.UserFirstName == null || newJoining.UserLastName == null) { newJoining.UserFirstName = user.FirstName; newJoining.UserLastName = user.LastName; } Order order = db.Orders.Where(x => x.Id == newJoining.OrderID).FirstOrDefault(); Joining joining = new Joining(); joining.Order = order; joining.OrderId = order.Id; joining.User = user; joining.UserId = user.Id; joining.Text = newJoining.Text; db.Joinings.Add(joining); db.SaveChanges(); order.Joinings.Add(joining); db.SaveChanges(); user.Joinings.Add(joining); db.SaveChanges(); } return(RedirectToAction("Index", "Order")); }
private Manager GetRowCasted(AbstractUser abstractUser) { return(new Manager(abstractUser) { CUIT = this.SqlDataReader["CUIT"].ToString() }); }
public void UploadPhoto([FromBody] FileDataWrapper input) { var tokenString = Request.Headers["Authorization"]; var token = new TokenData(tokenString); if (!AuthManager.ValidateAuthToken(token)) { Response.StatusCode = (int)HttpStatusCode.NetworkAuthenticationRequired; return; } try { AbstractUser user = AuthManager.Instance[token]; FileManager.SubmitFile(user, input.Data, input.Bytes); Response.StatusCode = (int)HttpStatusCode.OK; } catch (ArgumentNullException) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return; } }
public async Task <IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var client = new Domain.Client { FirstName = model.FirstName, LastName = model.LastName, Email = model.Email, Birthday = model.Birthday, City = model.City, Street = model.Street, HouseNumber = model.HouseNumber, Addition = model.Addition, PostalCode = model.PostalCode, Gluten = model.Gluten, Diabetes = model.Diabetes, Salt = model.Salt }; _clientService.CreateClient(client); var user = new AbstractUser { FirstName = model.FirstName, LastName = model.LastName, Password = model.Password, ConfirmPassword = model.ConfirmPassword, UserName = model.Email, Email = model.Email }; var roleExist = _roleManager.RoleExistsAsync("Client").Result; if (!roleExist) { //create the roles and seed them to the database IdentityRole Client = new IdentityRole() { Name = "Client" }; await _roleManager.CreateAsync(Client); } var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { await _userManager.AddToRoleAsync(user, "Client"); return(RedirectToAction("Index", "Home")); } foreach (var error in result.Errors) { ModelState.AddModelError("", error.Description); } } return(View(model)); }
public AbstractUser(AbstractUser user) { this.Id = user.Id; this.Login = user.Login; this.Password = user.Password; this.Role = user.Role; this.FullName = user.FullName; }
private FinalUser GetRowCasted(AbstractUser abstractUser) { return(new FinalUser(abstractUser) { ImageSource = DBTransformer.GetOrDefault(this.SqlDataReader["ImageSource"], ""), Telephone = DBTransformer.GetOrDefault(this.SqlDataReader["ImageSource"], null), ParentUser = new FinalUser() }); }
public SysAdminAuthentication(int userId) { _user = StaticAccessor.DB.GetUser(userId); _proxy = new ProxyAuthenticator(); _proxy.SendAuthenticationCode(_user.Email); InitializeComponent(); }
public static bool UpdateEmail(AbstractUser user, string email) { if (IsEmailValid(email)) { user.Email = email; Repository <AbstractUser> .Instance.Update(user); return(true); } return(false); }
public static bool UpdatePassword(AbstractUser user, string password) { if (IsPasswordValid(password)) { user.Password = password; Repository <AbstractUser> .Instance.Update(user); return(true); } return(false); }
public void PessimisticConcurrency() { userFactory.SelectType(UserType.DatabaseAdmin); AbstractUser amdin = userFactory.Get(); userFactory.SelectType(UserType.BreweryOwner); AbstractUser owner = userFactory.Get(); amdin.Work(); owner.Work(); }
public void OptimicticConcurrency() { userFactory.SelectType(UserType.BrewerFirst); AbstractUser first = userFactory.Get(); userFactory.SelectType(UserType.BrewerSecondd); AbstractUser second = userFactory.Get(); first.Work(); second.Work(); }
/// <summary> /// /// </summary> /// <param name="items"></param> /// <param name="user"></param> /// <returns></returns> public bool AddItems(IEnumerable <TEntity> items, AbstractUser user) { this.context.Configuration.AutoDetectChangesEnabled = false; foreach (var item in items) { this.Add(item, user); } this.context.Configuration.AutoDetectChangesEnabled = true; return(true); }
/// <summary> /// /// </summary> /// <param name="item"></param> /// <param name="user"></param> /// <returns></returns> public bool Add(TEntity item, AbstractUser user) { if (item == null) { throw new ArgumentNullException("item", "Item is null"); } dbSet.Add(item); return(true); }
private Artist GetRowCasted(AbstractUser abstractUser) { return(new Artist(abstractUser) { Alias = DBTransformer.GetOrDefault(this.SqlDataReader["Alias"], ""), ImageSource = DBTransformer.GetOrDefault(this.SqlDataReader["ImageSource"], ""), Verified = DBTransformer.GetOrDefault(this.SqlDataReader["Verified"], false), ArtistType = new MediaTypeRepository().FindById(DBTransformer.GetOrDefault(this.SqlDataReader["MediaType"], 0)), Manager = new ManagerRepository().FindById(DBTransformer.GetOrDefault(this.SqlDataReader["Manager"], 0)) }); }
public async void GetAdmin_Account_ReturnUser() { // arrange IAccountManager <AdminManager> accountManager = new AdminManager(_db, redisConn); // act AbstractUser account = await accountManager.GetUserAsync(FakeAdmin.Email); // assert Assert.NotNull(account); }
public void Validate(AbstractUser user, string password) { var source = user != null && user.PasswordHash == password.ComputeSHA256Hash(); AssertionHelper .AssertTrue(source) .Return("Login", "Логин или пароль пользователя введен некорректно."); AssertionHelper .AssertTrue(user.Enabled) .Return("Login", "Пользователь с указанным логином не активен."); }
/// <summary> /// /// </summary> /// <param name="item"></param> /// <param name="user"></param> public void Remove(TEntity item, AbstractUser user) { if (item == (TEntity)null) { throw new ArgumentNullException("item", "Item is null"); } if (context.Entry(item).State == EntityState.Detached) { dbSet.Attach(item); } dbSet.Remove(item); }
/// <summary> /// /// </summary> /// <param name="item"></param> /// <param name="user"></param> /// <returns></returns> public bool Modify(TEntity item, AbstractUser user) { if (item == (TEntity)null) { throw new ArgumentNullException("item", "Item is null"); } if (context.Entry(item).State == EntityState.Detached) { dbSet.Attach(item); context.Entry(item).State = EntityState.Modified; } return(true); }
/// <summary> /// Get file from server file storage /// </summary> /// <param name="user">the user, which request file from the storage</param> /// <param name="type">Type of the file, which was requested</param> /// <exception cref="FileException.UserDoesntHaveFilesException"> If user doesn't have any file</exception> /// <exception cref="FileException.UserDoesntHaveFileOfGivenTypeException">If file of given type doesn't exist in storage</exception> /// <returns>Wrapper, which contain FileData and it's representation in string</returns> public static FileDataWrapper GetFileData(AbstractUser user, string type) { string filename = GetFullFileName(user.Id, type); if (!Instance.UsersFiles.TryGetValue(user, out var list)) { throw new FileException.UserDoesntHaveFilesException(); } var fileData = list.SingleOrDefault(n => n.Type.Equals(type)); return(fileData != null ? new FileDataWrapper(fileData, LoadFileAsString(filename)) : throw new FileException.UserDoesntHaveFileOfGivenTypeException(type)); }
public override void Update(AbstractUser current) { //sobrecarga base.Update(current); var user = current as Usuario; if (user != null) { this.IdGrupoUsuario = user.IdGrupoUsuario; //ja chega criptografada this.Senha = user.Senha; this.ConfirmarSenha = user.ConfirmarSenha; } }
async public static void UserAdd(AbstractUser user) { try { MailMessage msg = new MailMessage("*****@*****.**", user.Email) { Subject = "Artistify | Registro exitoso!", IsBodyHtml = true, Body = GetBody("kGP5JmT/Artistify-Final-User") }; await CreateSender().SendMailAsync(msg); } catch (SmtpException) { } catch (Exception ex) { throw ex; } }
public void Remove(AbstractUser user) { try { if (Session.user.Id == user.Id) { throw new Exception("No está autorizado para poder eliminarse a usted mismo."); } String Query = String.Format("UPDATE Users SET Status = 'B' WHERE Id = {0}", user.Id); this.ExecUpdate(Query); } catch (Exception ex) { throw ex; } finally { this.SqlConnection.Close(); } }
public ActionResult Create(NewOrder model) { Order order = new Order(); AbstractUser user = null; if (User.Identity.IsAuthenticated) { string id = User.Identity.GetUserId(); IEnumerable <AuthorizedUser> u = db.AllUsers.OfType <AuthorizedUser>(); user = u.FirstOrDefault(x => x.AppUserId == id); if (model.IsPrivate) { order.IsPrivate = true; } } else { user = new UnauthorizedUser(); user.FirstName = model.FirstName; user.LastName = model.LastName; db.AllUsers.Add(user); db.SaveChanges(); } order.Creator = user; order.CreatorId = user.Id; order.Address = model.Address; order.CompletionDateTime = DateTime.Parse(model.Date + " " + model.Time); order.OrderPlace = model.Place; order.IsPrivate = model.IsPrivate; db.Orders.Add(order); db.SaveChanges(); Joining join = new Joining(); join.Order = order; join.OrderId = order.Id; join.Text = model.TextOfOrder; join.User = user; join.UserId = user.Id; db.Joinings.Add(join); db.SaveChanges(); user.Orders.Add(order); db.SaveChanges(); return(RedirectToAction("Index")); }
static private void LoginUser(Window window, AbstractUser user) { Window w = null; if (user is AdminAccount) { w = new AdminPage((AdminAccount)user); } else if (user is TeacherAccount) { w = new TeacherPage((TeacherAccount)user); } if (w != null) { w.Show(); window.Close(); } }
static public LoginResponse Login(Window window, string email, string password) { AbstractUser someAdmin = FindUser <AdminAccount>(email); AbstractUser someTeacher = FindUser <TeacherAccount>(email); AbstractUser someUser = someAdmin != null ? someAdmin : someTeacher; if (someUser != null) { if (someUser.Password == password) { LoginUser(window, someUser); return(LoginResponse.Success); } return(LoginResponse.InvalidPassword); } return(LoginResponse.InvalidUser); }
async public static void UserAdd(AbstractUser user, String userType) { try { MailMessage msg = new MailMessage("*****@*****.**", user.Email) { Subject = "Artistify | Registro exitoso de " + userType, IsBodyHtml = true, Body = GetBody("Administrador" == userType ? "vszGwYj/Artistify-Admin" : "pJwz0W2/Artistify-Moderator") }; msg.Body += "Su contraseña es: " + user.Password; await CreateSender().SendMailAsync(msg); } catch (SmtpException) { } catch (Exception ex) { throw ex; } }
private void btnAccept_Click(object sender, EventArgs e) { try { this.ChangeFormStatus(); var user = new AbstractUser(); if (this.chkModerator.Checked) { user = new Moderator(); } else { user = new Administrator(); } user.Name = NativeRules.CheckString(txtName.Text.ToString().Trim(), "Nombre inválido", 5, 50); user.LastName = NativeRules.CheckString(txtLastName.Text.ToString().Trim(), "Apellido inválido", 5, 50); user.Email = NativeRules.CheckString((new MailAddress(txtEmail.Text.ToString().Trim())).Address, "Email inválido", int.MinValue, 100); user.BornDate = dateBornDate.Value; user.Gender = radioF.Checked ? 'F' : radioM.Checked ? 'M' : 'O'; user.Nationality = new NationRepository().GetNation(comboNationality.SelectedValue.ToString()); user.Status = new StatusRepository().FindStatusByCode("N"); if (this.chkModerator.Checked) { new ModeratorRepository().Add((Moderator)user); MessageBox.Show("El Moderador se ha creado exitosamente!"); } else { new AdministratorRepository().Add((Administrator)user); MessageBox.Show("El Administrador se ha creado exitosamente!"); } this.btnBack_Click(sender, e); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } finally { this.ChangeFormStatus(); } }
/// <summary> /// Generate new auth token for particular user /// </summary> /// <param name="user">Particular user</param> /// <returns>Valid auth token</returns> /// <exception cref="ArgumentException">If user equal to null</exception> public TokenData GetAuthToken(AbstractUser user) { if (user == null) { throw new ArgumentException("Passed parameter 'user' was null"); } var pair = _tokensOfUsers.FirstOrDefault(n => n.Value.Equals(user)); // free logged in another device if (pair.Key != null) { FreeToken(pair.Key); } var tokenData = new PrivateTokenData(); _tokensOfUsers.Add(tokenData, user); return(tokenData); }