コード例 #1
0
 public void ValidateUsername_Valid_ReturnsTrue()
 {
     var av = new AccountValidation();
     bool validUsername = av.ValidateUsername("jesse123");
     Assert.IsTrue(validUsername);
 }
コード例 #2
0
 public void ValidateUsername_InvalidWithPlaceholder_ReturnsFalse()
 {
     var av = new AccountValidation();
     bool validUsername = av.ValidateUsername("enter your username..");
     Assert.IsFalse(validUsername);
 }
コード例 #3
0
        public IHttpActionResult CreateAccount(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                if (!ServiceContext.AccountMembershipService.VerifyUserExistence(model.UserName))
                {
                    //Verificar se existem usuários com o mesmo email informado, caso afirmativo desabilita-los
                    Services.ServiceContext.CustomerService.DisableUser(model.Email);
                    foreach (var user in ServiceContext.AccountMembershipService.GetUserByEmail(model.Email, 0, 100))
                    {
                        MembershipUser membershipUser = Membership.GetUser(user.UserName, true);
                        membershipUser.IsApproved = false;
                        Membership.UpdateUser(membershipUser);
                    }

                    // Attempt to register the user
                    MembershipCreateStatus createStatus = ServiceContext.AccountMembershipService.CreateUser(model);
                    if (createStatus == MembershipCreateStatus.Success)
                    {
                        //We must create a record on customer table
                        var customer = new Customer()
                        {
                            Email = model.Email,
                            //IDCity = 1,
                            Name          = model.UserName,
                            Address       = "-",
                            Phone1        = "-",
                            AddressNumber = "-",
                            UserName      = model.UserName,
                            CreateDate    = DateTime.Now,
                            CreatedBy     = model.UserName,
                            ModifyDate    = DateTime.Now,
                            ModifiedBy    = model.UserName,
                            Status        = (short)Model.InfraStructure.Enums.StatusType.Inactive,
                            ActivateKey   = Guid.NewGuid()
                        };
                        Services.ServiceContext.CustomerService.Insert(customer);

                        //todo:
                        //FormsService.SignIn(model.UserName, false /* createPersistentCookie */);

                        this.SavePreferences(customer, model.AllowNewsletter);
                        MembershipUser user = Membership.GetUser(model.UserName, true);
                        user.IsApproved = false;
                        Membership.UpdateUser(user);
                        ServiceContext.FormsAuthenticationService.SignOut();
                        this.SendEmailRegisterCode(model.IDCulture, customer);
                        //return this.Request.CreateResponse(HttpStatusCode.OK, new ResponseMessage(Internationalization.Message.User_Register_Code_Has_Been_Sent));
                        return(Ok(new { Message = Internationalization.Message.User_Register_Code_Has_Been_Sent }));
                    }
                    else
                    {
                        return(BadRequest(AccountValidation.ErrorCodeToString(createStatus)));
                    }
                    //return this.Request.CreateResponse(HttpStatusCode.NotAcceptable, AccountValidation.ErrorCodeToString(createStatus));
                }
                else
                {
                    return(BadRequest(Internationalization.Message.Choose_Another_Username));
                    //return this.Request.CreateResponse(HttpStatusCode.NotAcceptable, Internationalization.Message.Choose_Another_Username);
                }
            }
            else
            {
                return(BadRequest(ModelState));
                //return this.Request.CreateResponse(HttpStatusCode.NotAcceptable, Internationalization.Message.Error);
            }
        }
コード例 #4
0
 public abstract ValidationResult Validate(AccountValidation data);
コード例 #5
0
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                UserCredential credential = null;

                try
                {
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        new ClientSecrets
                    {
                        ClientId     = ClientId,
                        ClientSecret = ClientSecret
                    },
                        Scopes,
                        "user",
                        CancellationToken.None,
                        Oauth
                        ).Result;


                    var plusService = new PlusService(
                        new BaseClientService.Initializer
                    {
                        HttpClientInitializer = credential,
                        ApplicationName       = "app2-s8"
                    }
                        );
                    var userProfile = plusService.People.Get("me").Execute();
                    var userEmail   = userProfile.Emails[0].Value;

                    if (MembershipService.ValidateUser(userProfile.DisplayName, userProfile.Id))
                    {
                        FormsService.SignIn(userProfile.DisplayName, false /* createPersistentCookie */);
                        //Encode the username in base64
                        byte[]     toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(userProfile.DisplayName);
                        HttpCookie authCookie      = new HttpCookie("username", System.Convert.ToBase64String(toEncodeAsBytes));
                        HttpContext.Response.Cookies.Add(authCookie);
                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        MembershipCreateStatus createStatus = MembershipService.CreateUser(userProfile.DisplayName, userProfile.Id, userEmail);
                        if (createStatus == MembershipCreateStatus.Success)
                        {
                            FormsService.SignIn(userProfile.DisplayName, false /* createPersistentCookie */);
                            //Encode the username in base64
                            byte[]     toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(userProfile.DisplayName);
                            HttpCookie authCookie      = new HttpCookie("username", System.Convert.ToBase64String(toEncodeAsBytes));
                            HttpContext.Response.Cookies.Add(authCookie);
                            return(RedirectToAction("Index", "Home"));
                        }
                        else
                        {
                            ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                        }
                    }
                }
                catch (Exception ex)
                {
                    credential = null;
                    ModelState.AddModelError("", ex.ToString());
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #6
0
        private AccountEntity ValidateAccountEntity(string accName)
        {
            AccountValidation accountValidation = new AccountValidation(new RepositoryFactory <AccountEntity>(), ConnString);

            return(accountValidation.ValidateAccount(accName, "s", true).Account);
        }
コード例 #7
0
        public ActionResult Register(RegisterModel register, FormCollection collection)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                if (string.IsNullOrEmpty(register.Name))
                {
                    register.Name = register.UserName;
                }
                register.UserName = register.UserName.Trim();
                register.Email    = register.Email.Trim();

                MembershipCreateStatus createStatus = MembershipService.CreateUser(register.UserName, register.Password, register.Email, false);

                if (createStatus == MembershipCreateStatus.Success)
                {
                    string[] roles = { "Guest" };
                    if (Roles.IsUserInRole("Administrator"))
                    {
                        roles = (collection.GetValues("RoleChecks")).ToArray();
                        string[] allRoles = Roles.GetAllRoles();
                        for (int i = 0; i < roles.Count(); i++)
                        {
                            int j = int.Parse(roles[i]) - 1;
                            roles[i] = allRoles[j];
                        }

                        // Approve the user
                        MembershipUser newUser = Membership.GetUser(register.UserName);
                        newUser.IsApproved = true;
                        Membership.UpdateUser(newUser);
                    }
                    else
                    {
                        string urlBase = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath;
                        RegisterSendingMail(register.UserName, urlBase);
                    }
                    register.Role = roles;

                    Roles.AddUserToRoles(register.UserName, register.Role);

                    UpdateMemberInfo(register);

                    //if (register.InitiateTypeID == 1 || register.InitiateTypeID == 2)
                    //{
                    //    //int temp = register.InitiateTypeID;
                    //    //register.InitiateTypeID = 5;
                    //    //UpdateMemberInfo(register);
                    //    //register.InitiateTypeID = temp;
                    //    TempData["register"] = register;
                    //    return RedirectToAction("Create", "MemberInfo");
                    //}
                    return(RedirectToAction("RegisterConfirmation", new { initiate = false }));
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            ViewData["InitiateTypes"]  = _entities.InitiateTypes.ToList();

            return(View(register));
        }
コード例 #8
0
        public ActionResult Register(RegisterModel model)
        {
            Felbook.Helpers.ImageHelper imageOperator = new Felbook.Helpers.ImageHelper(); //pomocná třída pro operace s obrázky
            HttpPostedFileBase          imageToUpload = Request.Files["profileimage"];
            bool uploadImage = false;

            if (imageToUpload.ContentLength == 0)
            {
                uploadImage = false;
            }
            else if (Felbook.Helpers.ImageHelper.IsImage(imageToUpload.ContentType))
            {
                uploadImage = true;
            }
            else
            {
                ModelState.AddModelError("file", "Your file wasn't image.");
            }

            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus = MembershipService.CreateUser(model);
                if (createStatus == MembershipCreateStatus.Success)
                {
                    FormsService.SignIn(model.UserName, false /* createPersistentCookie */);

                    //upload user profile image
                    User   actualUser = Model.UserService.FindByUsername(model.UserName);
                    int    userId     = actualUser.Id;
                    string fileDir    = "../Web_Data/profile_images/";
                    //název souboru je vždy stejný
                    string fileName     = "profileimage.png";
                    string fileFullPath = Path.Combine(HttpContext.Server.MapPath(fileDir + userId), fileName);
                    string fileDirPath  = Path.GetDirectoryName(fileFullPath);

                    try
                    {
                        //pokusíme se vytvořit adresář
                        Directory.CreateDirectory(fileDirPath);
                    }
                    //jednotlivě odchytávám chyby
                    catch (UnauthorizedAccessException)
                    {
                        ModelState.AddModelError("file", "Upload wasn´t successful");
                    }
                    catch (Exception)
                    {
                        ModelState.AddModelError("file", "Some uknown error");
                    }

                    if (uploadImage == true)
                    {
                        imageOperator.ImageResize(imageToUpload, fileFullPath, 90, 120);
                    }
                    else
                    {
                        //zjistím si cesty k souboru
                        string sourceFile = Path.Combine(HttpContext.Server.MapPath(fileDir + "/default/"), fileName);
                        string destFile   = System.IO.Path.Combine(fileDirPath, fileName);

                        //kopíruje to soubor
                        System.IO.File.Copy(sourceFile, destFile, true);
                    }
                    return(RedirectToAction("Index", "Profile", new { username = actualUser.Username }));
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }

            // If we got this far, something failed, redisplay form
            ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
            return(View(model));
        }
コード例 #9
0
        public ActionResult Head(itmmAdminHead model, int section)
        {
            var r = from y in con.Laboratories
                    where y.inactive == 0
                    orderby y.LaboratoryName ascending
                    select y;

            ViewBag.LabList = r;

            var b = from y in con.Laboratory_Head
                    select y;

            ViewBag.HeadList = b;

            if (ModelState.IsValid)
            {
                AccountMembershipService MembershipService = new AccountMembershipService();
                MembershipCreateStatus   createStatus      = MembershipService.CreateUser(model.uname, model.password, model.eadd);
                if (createStatus == MembershipCreateStatus.Success)
                {
                    Roles.AddUserToRole(model.uname, "Head");
                    Laboratory_Head a = new Laboratory_Head();
                    a.FirstName    = model.fname;
                    a.LastName     = model.lname;
                    a.UserName     = model.uname;
                    a.ContactNum   = model.cnum;
                    a.EmailAdd     = model.eadd;
                    a.LaboratoryId = section;


                    con.AddToLaboratory_Head(a);

                    var x = (from y in con.Laboratories
                             where y.LaboratoryId == section
                             select y).FirstOrDefault();


                    if (x == null) // when lab recors is not exist
                    {
                        x.UserName    = model.uname;
                        x.DateUpdated = DateTime.Now;
                        con.AddToLaboratories(x);
                    }
                    else
                    {
                        x.UserName    = model.uname;
                        x.DateUpdated = DateTime.Now;
                    }


                    con.SaveChanges();

                    return(RedirectToAction("Head", "AdminBold"));
                }
                else
                {
                    ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
                }
            }
            return(View(model));
        }