Ejemplo n.º 1
0
        public static InvitationToken Create(DbContext db, String email, User inviter, 
            Organization organization, List<String> roles, List<Region> regions)
        {
            var UserStore = new CUserStore<User>(db);
            var UserManager = new UserManager<User>(UserStore);
            var RoleManager = new RoleManager<Role>(new CRoleStore<Role>(db));

            InvitationToken result = new InvitationToken();
            while(result.Token == null)
            {
                var token = GenerateToken();
                var exists = db.Set<InvitationToken>().Any(i => i.Token == token);
                if (!exists)
                    result.Token = token;
            }
            User user = new User();
            user.Email = email;
            user.UserName = email;
            user.fkOrganizationId = organization.Id;
            user.Id = Guid.NewGuid().ToString();
            user.Organization = organization;

            var userRes = UserManager.Create(user);
            if (!userRes.Succeeded)
                throw new ApplicationException(userRes.Errors.First());

            result.User = user;
            result.fkInviterId = inviter.Id;
            result.fkUserId = user.Id;
            db.Set<InvitationToken>().Add(result);
            db.SaveChanges();

            result.Inviter = inviter;
            result.User = user;

            foreach(var role in roles)
            {
                var res = UserManager.AddToRole(user.Id, role);
                Console.WriteLine(res);
            }
            foreach(var region in regions)
            {
                var scope = new UserScope
                {
                    fkUserId = user.Id,
                    fkRegionId = region.Id
                };
                db.Set<UserScope>().Add(scope);
            }
            db.SaveChanges();

            return result;
        }
Ejemplo n.º 2
0
        public static InvitationToken Create(DbContext db, String email, User inviter, 
            Organization organization, List<String> roles, List<Region> regions)
        {
            var UserStore = new CUserStore<User>(db);
            var UserManager = new UserManager<User>(UserStore);
            var RoleManager = new RoleManager<Role>(new CRoleStore<Role>(db));

            InvitationToken result = new InvitationToken();
            result.Token = GenerateToken();
            User user = new User();
            user.Email = email;
            user.UserName = email;
            user.fkOrganizationId = organization.Id;
            user.Id = Guid.NewGuid().ToString();
            user.Organization = organization;

            UserManager.Create(user);

            result.User = user;
            result.fkInviterId = inviter.Id;
            result.fkUserId = user.Id;
            db.Set<InvitationToken>().Add(result);
            db.SaveChanges();

            result.Inviter = inviter;
            result.User = user;

            foreach(var role in roles)
            {
                var res = UserManager.AddToRole(user.Id, role);
                Console.WriteLine(res);
            }
            foreach(var region in regions)
            {
                var scope = new UserScope
                {
                    fkUserId = user.Id,
                    fkRegionId = region.Id
                };
                db.Set<UserScope>().Add(scope);
            }
            db.SaveChanges();

            return result;
        }
Ejemplo n.º 3
0
 public KawalDesaIdentity(User user, string type)
     : base(user.UserName, type)
 {
     User = user;
 }
Ejemplo n.º 4
0
        public ActionResult FacebookRedirect(String code, String token, String exAuthState)
        {
            String loginRedirect = Session["LoginRedirect"] as string;
            if (loginRedirect == null)
                loginRedirect = "/";
            Session["LoginRedirect"] = null;

            if (String.IsNullOrEmpty(code))
            {
                return new RedirectResult(loginRedirect);
            }

            string accessToken = null;
            String facebookID = null;
            String name = null;
            bool isVerified = false;

            try
            {
                String clientID = ConfigurationManager.AppSettings[FacebookClientIDConfig];
                String secretKey = ConfigurationManager.AppSettings[FacebookSecretKeyConfig];
                var redirectHost = GetRedirectHost();
                var redirectUrl = redirectHost + "/FacebookRedirect";
                if (!string.IsNullOrWhiteSpace(token))
                    redirectUrl += "?token=" + token;
                if (!string.IsNullOrWhiteSpace(exAuthState))
                    redirectUrl += "?exAuthState="+exAuthState;

                string url = "https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}";
                WebRequest request = WebRequest.Create(string.Format(url, clientID, redirectUrl, secretKey, code));

                using (WebResponse response = request.GetResponse())
                using (Stream stream = response.GetResponseStream())
                {
                    Encoding encode = Encoding.GetEncoding("utf-8");
                    using (StreamReader streamReader = new StreamReader(stream, encode))
                    {
                        accessToken = streamReader.ReadToEnd().Replace("access_token=", "");
                    }
                }

                Session["FacebookAccessToken"] = accessToken;

                string meUrl = "https://graph.facebook.com/me?access_token={0}";
                request = WebRequest.Create(string.Format(meUrl, accessToken));
                using (WebResponse response = request.GetResponse())
                using (Stream stream = response.GetResponseStream())
                {
                    Encoding encode = Encoding.GetEncoding("utf-8");
                    using (StreamReader streamReader = new StreamReader(stream, encode))
                    {
                        var userDict = JsonConvert.DeserializeObject<IDictionary<String, Object>>(streamReader.ReadToEnd());
                        facebookID = userDict["id"] as string;
                        name = userDict["name"] as string;
                        isVerified = (bool) userDict["verified"];
                    }
                }
            }
            catch (Exception e)
            {
                logger.Error("facebook graph error, token:" + accessToken, e);
            }

            if (facebookID != null)
            {
                using (DB db = new DB())
                {
                    InvitationToken invitationToken = null;
                    if (!string.IsNullOrWhiteSpace(token))
                    {
                        token = token.Trim();
                        invitationToken = db.InvitationTokens.FirstOrDefault(t => t.Token == token && !t.IsUsed);
                    }

                    var user = db.Users.FirstOrDefault(u => u.FacebookId == facebookID && u.IsActive);
                    if(invitationToken != null)
                    {
                        using (var tx = db.Database.BeginTransaction())
                        {
                            invitationToken.IsUsed = true;
                            db.Entry(invitationToken).State = EntityState.Modified;
                            if (user != null)
                            {
                                user.IsADuplicate = true;
                                user.IsActive = false;
                                user.UserName = "******" + user.Id.Replace("-", "");
                                db.Entry(user).State = EntityState.Modified;

                                foreach (var spreadsheet in db.Set<Spreadsheet>().Where(d => d.fkCreatedById == user.Id))
                                {
                                    spreadsheet.fkCreatedById = invitationToken.fkUserId;
                                    db.Entry(spreadsheet).State = EntityState.Modified;
                                }
                                foreach (var spreadsheet in db.Set<Spreadsheet>().Where(d => d.fkApprovedById == user.Id))
                                {
                                    spreadsheet.fkApprovedById = invitationToken.fkUserId;
                                    db.Entry(spreadsheet).State = EntityState.Modified;
                                }
                            }
                            user = invitationToken.User;
                            user.IsActive = true;
                            user.FacebookId = facebookID;
                            user.Name = name;

                            db.SaveChanges();
                            tx.Commit();
                        }
                    }

                    if (user == null)
                    {
                        using (var tx = db.Database.BeginTransaction())
                        {
                            var userManager = new UserManager<User>(new CUserStore<User>(db));
                            user = new User
                            {
                                FacebookId = facebookID,
                                Name = name,
                                IsActive = true,
                                UserName = "******" + facebookID,
                                Id = Guid.NewGuid().ToString(),
                                FacebookIsVerified = isVerified
                            };
                            var newUser = userManager.Create(user);
                            userManager.AddToRole(user.Id, Role.VOLUNTEER);
                            tx.Commit();
                        }
                    }

                    Session[USERID_KEY] = user.Id;
                }
            }

            if(!string.IsNullOrEmpty(exAuthState))
                return new RedirectResult("/AuthTokenGet?state="+exAuthState);

            return new RedirectResult(loginRedirect);
        }
Ejemplo n.º 5
0
        public void CreateUser(string city, string street, int streetnumber, decimal latitude, decimal longitude, int regionid, string firstname, string surname, string username, string email, string password)
        {
            try
            {
                var adr = new Address();
                adr.City = city;
                adr.Street = street;
                adr.StreetNumber = streetnumber;
                adr.Latitude = latitude;
                adr.Longitude = longitude;
                adr.RegionId = regionid;

                this.UnitOfWork.AddressRepository.Insert(adr);

                var pers = new Person();
                pers.FirstName = firstname;
                pers.SurName = surname;
                pers.Address = adr;

                this.UnitOfWork.PersonRepository.Insert(pers);

                var roleid = this.UnitOfWork.RoleRepository.Get().Where(r => r.Name == "Administrator").FirstOrDefault().Id;

                var usr = new User();
                usr.UserName = username;
                usr.PasswordSalt = BCrypt.Net.BCrypt.GenerateSalt(12);
                usr.Password = BCrypt.Net.BCrypt.HashPassword(password, usr.PasswordSalt);
                usr.Rating = 10;
                usr.Email = email;
                usr.RoleId = roleid;
                usr.Person = pers;

                this.UnitOfWork.UserRepository.Insert(usr);
                this.UnitOfWork.Save();
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }

            }
        }
Ejemplo n.º 6
0
        public void ChangeUser(string city, string street, int streetnumber, int regionid, string firstname, string surname, string address, string username, string email, string password)
        {
            var adr = new Address();
            adr.City = city;
            adr.Street = street;
            adr.StreetNumber = streetnumber;
            adr.RegionId = regionid;

            this.UnitOfWork.AddressRepository.Insert(adr);

            var pers = new Person();
            pers.FirstName = firstname;
            pers.SurName = surname;
            pers.Address = adr;

            this.UnitOfWork.PersonRepository.Insert(pers);

            var usr = new User();
            usr.UserName = username;
            usr.Password = password;
            usr.RoleId = 1;
            usr.Person = pers;

            this.UnitOfWork.UserRepository.Insert(usr);
        }
Ejemplo n.º 7
0
        public ActionResult Create(ReUzze.Models.UserViewModel viewModel)
        {
            try
            {
                // Check if there are roles in the database
                var roles = this.UnitOfWork.RoleRepository.Get().Count();
                if (roles == 0)
                {
                    var model = new ReUzze.Models.UserViewModel
                    {
                        StatusMessage = "There are no roles in the database ...",
                        Roles = new SelectList(this.UnitOfWork.RoleRepository.Get(), "Id", "Name"),
                        Regions = new SelectList(this.UnitOfWork.RegionRepository.Get(), "Id", "Name")
                    };
                    return View(model);
                }

                // Check if there are regions in database
                var regions = this.UnitOfWork.RegionRepository.Get().Count();
                if (regions == 0)
                {
                    var model = new ReUzze.Models.UserViewModel
                    {
                        StatusMessage = "There are no regions in the database ...",
                        Roles = new SelectList(this.UnitOfWork.RoleRepository.Get(), "Id", "Name"),
                        Regions = new SelectList(this.UnitOfWork.RegionRepository.Get(), "Id", "Name")
                    };
                    return View(model);
                }

                // Check if user has selected region
                if (viewModel.SelectRegionId == 0)
                {
                    var model = new ReUzze.Models.UserViewModel
                    {
                        StatusMessage = "You need to select a region!",
                        Roles = new SelectList(this.UnitOfWork.RoleRepository.Get(), "Id", "Name"),
                        Regions = new SelectList(this.UnitOfWork.RegionRepository.Get(), "Id", "Name")
                    };
                    return View(model);
                }

                // Check if user has selected role
                if (viewModel.SelectRoleId == 0)
                {
                    var model = new ReUzze.Models.UserViewModel
                    {
                        StatusMessage = "You need to select a role!",
                        Roles = new SelectList(this.UnitOfWork.RoleRepository.Get(), "Id", "Name"),
                        Regions = new SelectList(this.UnitOfWork.RegionRepository.Get(), "Id", "Name")
                    };
                    return View(model);
                }

                // Check if username already exists
                var usrname = this.UnitOfWork.UserRepository.Get().Where(u => u.UserName == viewModel.UserName).Count();
                if (usrname != 0)
                {
                    var model = new ReUzze.Models.UserViewModel
                    {
                        StatusMessage = "Please choose another username. This one already exists.",
                        Roles = new SelectList(this.UnitOfWork.RoleRepository.Get(), "Id", "Name"),
                        Regions = new SelectList(this.UnitOfWork.RegionRepository.Get(), "Id", "Name")
                    };
                    return View(model);
                }

                // Check if user email already exists
                var email = this.UnitOfWork.UserRepository.Get().Where(u => u.Email == viewModel.Email).Count();
                if (email != 0)
                {
                    var model = new ReUzze.Models.UserViewModel
                    {
                        StatusMessage = "This email address is already registered.",
                        Roles = new SelectList(this.UnitOfWork.RoleRepository.Get(), "Id", "Name"),
                        Regions = new SelectList(this.UnitOfWork.RegionRepository.Get(), "Id", "Name")
                    };
                    return View(model);
                }

                if (!ModelState.IsValid)
                {
                    var model = new ReUzze.Models.UserViewModel
                    {
                        Roles = new SelectList(this.UnitOfWork.RoleRepository.Get(), "Id", "Name"),
                        Regions = new SelectList(this.UnitOfWork.RegionRepository.Get(), "Id", "Name")
                    };
                    return View(model);
                }

                // ADDRESS
                var address = new Address();
                address.City = viewModel.City;
                address.Street = viewModel.Street;
                address.StreetNumber = viewModel.StreetNumber;
                address.Latitude = viewModel.Latitude;
                address.Longitude = viewModel.Longitude;
                address.RegionId = viewModel.SelectRegionId;

                this.UnitOfWork.AddressRepository.Insert(address);

                // PERSON
                var person = new Person();
                person.FirstName = viewModel.FirstName;
                person.SurName = viewModel.SurName;
                person.Address = address;
                this.UnitOfWork.PersonRepository.Insert(person);

                // USER

                var user = new User();
                user.UserName = viewModel.UserName;
                user.Email = viewModel.Email;
                user.PasswordSalt = BCrypt.Net.BCrypt.GenerateSalt(12);
                user.Password = BCrypt.Net.BCrypt.HashPassword(viewModel.Password, user.PasswordSalt);
                user.Rating = 10;
                user.RoleId = viewModel.SelectRoleId;
                user.Person = person;
                this.UnitOfWork.UserRepository.Insert(user);

                // ROLE NEEDS TO BE ADDED TO USER

                this.UnitOfWork.Save();

                return RedirectToAction("Index", "User");
            }
            catch (DbEntityValidationException dbEx)
            {
                foreach (var validationErrors in dbEx.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                    }
                }

            }

            return RedirectToAction("Create", "User");
        }
Ejemplo n.º 8
0
 public void AddNewUserJens()
 {
     UnitOfWork uow = new UnitOfWork();
     User user = new User();
     user.NickName = "jensdewulf";
     Person person = new Person();
     person.FirstName = "Jens";
     person.LastName = "De Wulf";
     person.Type = "Administrator";
     user.Person = person;
     user.Email = "*****@*****.**";
     uow.UserRepository.Insert(user);
     uow.Save();
 }
Ejemplo n.º 9
0
        public void AddRandomMember()
        {
            // Generate random characters
            var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

            // First name random generation
            var random = new Random();
            var firstrandom = new string(
                Enumerable.Repeat(chars, 8)
                          .Select(s => s[random.Next(s.Length)])
                          .ToArray());

            // Second name random generation
            var random2 = new Random();
            var secondrandom = new string(
                Enumerable.Repeat(chars, 8)
                          .Select(s => s[random2.Next(s.Length)])
                          .ToArray());

            // Add new character
            UnitOfWork uow = new UnitOfWork();

            // Create new member
            Member member = new Member();
            User user = new User();

            // Create new person
            Person person = new Person();
            person.FirstName = firstrandom.ToString();
            person.LastName = secondrandom.ToString();
            person.Type = "Administrator";

            // Set member nickname, email, password & salt
            member.NickName = firstrandom.ToString();
            member.Email = firstrandom + "." + secondrandom + "@gmail.com";
            member.Password = "******";
            member.Salt = "";
            member.ConfirmationToken = "ABC";

            // Assign new person to member (foreign keys)
            member.Person = person;

            uow.MemberRepository.Insert(member);
            uow.Save();
        }
Ejemplo n.º 10
0
 public void AddNewUserNico()
 {
     UnitOfWork uow = new UnitOfWork();
     User user = new User();
     user.NickName = "nicoverbruggen";
     Person person = new Person();
     person.FirstName = "Nico";
     person.LastName = "Verbruggen";
     person.Type = "Administrator";
     user.Person = person;
     user.Email = "*****@*****.**";
     uow.UserRepository.Insert(user);
     uow.Save();
 }