Exemplo n.º 1
0
        public ActionResult Register(RegisterViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {                 // Adding Member
                Member mem = new Member();
                mem.FirstName  = model.FirstName;
                mem.LastName   = model.LastName;
                mem.EmailId    = model.UserEmailId;
                mem.CreatedOn  = DateTime.Now;
                mem.ModifiedOn = DateTime.Now;
                mem.Password   = EncryptDecrypt.Encrypt(model.Password, true);
                mem.IsActive   = true;
                mem.IsDelete   = false;
                _unitOfWork.GetRepositoryInstance <Member>().Add(mem);
                // Adding Member Role
                MemberRole mem_Role = new MemberRole();
                mem_Role.MemberId = mem.MemberId;
                mem_Role.RoleId   = 2;
                _unitOfWork.GetRepositoryInstance <MemberRole>().Add(mem_Role);

                TempData["VerificationLinlMsg"]      = "You are registered successfully.";
                Session["MemberId"]                  = mem.MemberId;
                Response.Cookies["MemberName"].Value = mem.FirstName + " " + mem.LastName;
                Response.Cookies["MemberRole"].Value = "User";
                return(RedirectToAction("Index", "Home"));
            }
            return(View("Register", model));
        }
Exemplo n.º 2
0
        // update
        public bool UpdateMemberRole(int id, MemberRoleModel memberRole)
        {
            using (AttenderEntities ef = new AttenderEntities())
            {
                MemberRole updateMemberRole = ef.MemberRoles.FirstOrDefault(a => a.Id == id);
                if (updateMemberRole == null)
                {
                    return(false);
                }

                //updateMemberRole.Id = memberRole.Id;
                updateMemberRole.MemberId     = memberRole.MemberId;
                updateMemberRole.UniversityId = memberRole.UniversityId;
                updateMemberRole.Role         = memberRole.Role;

                try
                {
                    ef.Database.ExecuteSqlCommand($"UPDATE [dbo].[MemberRole] SET [MemberId] = {updateMemberRole.MemberId},[UniversityId] = {updateMemberRole.UniversityId},[Role] = { updateMemberRole.Role} WHERE [Id] = {id}");
                    //ef.SaveChanges();
                }
                catch
                {
                    return(false);
                }
            }
            return(true);
        }
Exemplo n.º 3
0
 public void AddRole(MemberRole role)
 {
     if (!IsRole(role))
     {
         roles.Add(role);
     }
 }
Exemplo n.º 4
0
        public override string Execute()
        {
            Console.WriteLine($"Trying to update the role of {User} in project {Project}...");

            string message;

            var project = _projectService.GetProjectByName(Project).Result;
            var user    = _accountService.GetUserByUserName(User).Result;
            var roleId  = MemberRole.GetMemberRoleId(Role);

            if (project != null && user != null && roleId > 0)
            {
                var projectMember = _projectMemberService.GetProjectMemberByUserId(project.Id, int.Parse(user.Id)).Result;

                if (projectMember != null)
                {
                    _projectMemberService.UpdateProjectMember(project.Id, projectMember.Id, new UpdateProjectMemberDto
                    {
                        Id     = projectMember.Id,
                        UserId = int.Parse(user.Id),
                        ProjectMemberRoleId = roleId
                    }).Wait();

                    message = $"User {User} has been assigned as {Role} in project {Project}";
                    Logger.LogInformation(message);
                    return(message);
                }
            }

            message = $"Failed to update user {User}. Make sure the project name and user email are correct.";

            return(message);
        }
Exemplo n.º 5
0
 public InvitationReceivedEvent(string groupTitle, string inviterName, int invitedId, MemberRole suggestedRole)
 {
     GroupTitle    = groupTitle;
     InviterName   = inviterName;
     InvitedId     = invitedId;
     SuggestedRole = suggestedRole;
 }
Exemplo n.º 6
0
        public async Task <IActionResult> Edit(int id, [Bind("MemberRoleId,MemberRoleName")] MemberRole memberRole)
        {
            if (id != memberRole.MemberRoleId)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(memberRole);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!MemberRoleExists(memberRole.MemberRoleId))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(memberRole));
        }
Exemplo n.º 7
0
 internal Member(int userId, MemberRole memberRole)
 {
     UserId           = userId;
     MemberRole       = memberRole;
     Paid             = false;
     CurriculumStatus = MemberCurriculumStatus.InProgress;
 }
Exemplo n.º 8
0
        public GroupShareViewModel(string roomId)
        {
            if (string.IsNullOrWhiteSpace(roomId))
            {
                return;
            }
            Snackbar = new SnackbarMessageQueue();
            room     = new Room()
            {
                id = roomId
            }.GetByRoomId();

            if (room != null)
            {
                var memlist = new DataofMember()
                {
                    groupid = room.id
                }.GetListByRoomId();
                if (memlist.Count == 0)
                {
                    APIHelper.GetRoomDetialByRoomId(room.id);
                    memlist = new DataofMember()
                    {
                        groupid = room.id
                    }.GetListByRoomId();
                }
                var user = memlist.FirstOrDefault(m => m.userId == Applicate.MyAccount.userId /*查询出自己的身份编号*/);
                role            = user.role;
                AllowUploadFile = room.allowUploadFile == 1 || user.role != MemberRole.Member;
            }
            uploadList = new ObservableCollection <RoomShare>();
            GetRoomShare();
            RegisterMessengers();
        }
        public ContentResult UnAssignMemberRoleByID(long MemberID, long[] UnAssignRoles)
        {
            Member member = Members.GetBy(MemberID);

            foreach (long RoleID in UnAssignRoles)
            {
                Role role = Roles.GetBy(RoleID);

                // Ignore admin in admins role
                if (member.Name.ToLower() == "admin" && role.Name.ToLower() == "admins")
                {
                }
                else
                {
                    MemberRole memberrole = new MemberRole();
                    memberrole.MemberID = MemberID;
                    memberrole.RoleID   = RoleID;
                    memberrole.Delete();
                }
            }

            String Json = Roles.JsonCollection(Roles.GetByMember(MemberID));

            return(Content(Json, TypeJson));
        }
Exemplo n.º 10
0
        public override string Execute()
        {
            Console.WriteLine($"Trying to get members of project {Project}...");

            string message;

            var project = _projectService.GetProjectByName(Project).Result;

            if (project != null)
            {
                var roleId         = MemberRole.GetMemberRoleId(Role ?? string.Empty);
                var projectMembers = _projectMemberService.GetProjectMembers(project.Id, roleId).Result;

                message = projectMembers.Select(m => new MemberListViewModel
                {
                    UserId   = m.UserId,
                    Username = m.Username,
                    Role     = m.ProjectMemberRoleName
                }).ToListCliString($"Found {projectMembers.Count} project member(s):");
            }
            else
            {
                message = $"Project {Project} was not found";
            }

            return(message);
        }
        public ActionResult Create([Bind(Include = "MemberId,FirstName,LastName,EmailId,Password,IsActive,IsDelete,CreatedOn,ModifiedOn,VendorName")] Member member)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    member.IsDelete   = false;
                    member.IsActive   = true;
                    member.VendorName = null;
                    member.Password   = EncryptDecrypt.Encrypt(member.Password, true);
                    unitOfWork.GetRepositoryInstance <Member>().Add(member);

                    MemberRole memberRole = new MemberRole();
                    memberRole.MemberId = member.MemberId;
                    memberRole.RoleId   = 1;
                    unitOfWork.GetRepositoryInstance <MemberRole>().Add(memberRole);
                    return(RedirectToAction("Index"));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }



            return(View("Index"));
        }
 public InvitationReceivedMessage(string groupTitle, string inviterName, MemberRole suggestedRole,
                                  string receiverName)
 {
     GroupTitle    = groupTitle;
     InviterName   = inviterName;
     SuggestedRole = suggestedRole;
     ReceiverName  = receiverName;
 }
Exemplo n.º 13
0
 public MemberDto(int id, int userId, MemberRole memberRole, bool paid, MemberCurriculumStatus curriculumStatus)
 {
     Id               = id;
     UserId           = userId;
     MemberRole       = memberRole;
     Paid             = paid;
     CurriculumStatus = curriculumStatus;
 }
Exemplo n.º 14
0
        public ActionResult DeleteConfirmed(Guid id)
        {
            MemberRole memberrole = db.MemberRoles.Find(id);

            db.MemberRoles.Remove(memberrole);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
Exemplo n.º 15
0
 internal Member(int userId, MemberRole memberRole,
                 bool paid, MemberCurriculumStatus curriculumStatus)
 {
     UserId           = userId;
     MemberRole       = memberRole;
     Paid             = paid;
     CurriculumStatus = curriculumStatus;
 }
Exemplo n.º 16
0
        // Sending Mail by passportId
        public void SendMailsByPassportId(string passportId)
        {
            System.Net.Mail.MailMessage mailMessage = new System.Net.Mail.MailMessage();

            using (AttenderEntities ef = new AttenderEntities())
            {
                Member member = ef.Members.FirstOrDefault(a => a.PassportNumber == passportId);
                if (member != null)
                {
                    MemberRole role = ef.MemberRoles.FirstOrDefault(a => a.MemberId == member.Id);
                    if (role != null)
                    {
                        memberRole = new MemberRoleModel()
                        {
                            Id           = role.Id,
                            MemberId     = role.MemberId,
                            UniversityId = role.UniversityId,
                            Role         = role.Role
                        };
                    }
                    if (role.Role == "s")
                    {
                        Random rnd        = new Random();
                        int    num        = rnd.Next();
                        string res        = num.ToString();
                        string hashedData = ComputeSha256Hash(res);

                        // updating password in the database with hashed password
                        UpdatePassword(member.Id, member, hashedData);

                        mailMessage.To.Add(member.Mail);
                        mailMessage.Subject = "Attender Registration";
                        mailMessage.Body    = "Dear " + member.FirstName + " " + member.LastName + "," + Environment.NewLine +
                                              "Please follow the instructions and enter your credentials in the website bellow:"
                                              + Environment.NewLine + "Your disposable password is: " + res + Environment.NewLine + "http://*****:*****@gmail.com", "Attender App");

                        mailMessage.Attachments.Add(new System.Net.Mail.Attachment("C:\\Users\\barpi\\Desktop\\Attender\\Instrutions Finding Mac address.pdf"));

                        SmtpClient stmpMail = new SmtpClient();
                        stmpMail.Host        = "smtp.gmail.com";
                        stmpMail.Credentials = new NetworkCredential("*****@*****.**", "Attender");
                        stmpMail.EnableSsl   = true;
                        stmpMail.Port        = 587;

                        try
                        {
                            stmpMail.Send(mailMessage);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message.ToString());
                        }
                    }
                }
            }
        }
Exemplo n.º 17
0
 public MemberInfo(int userId, string name, string avatarLink, MemberRole role, bool paid,
                   MemberCurriculumStatus curriculumStatus)
 {
     UserId           = userId;
     Name             = name;
     AvatarLink       = avatarLink;
     Role             = role;
     Paid             = paid;
     CurriculumStatus = curriculumStatus;
 }
Exemplo n.º 18
0
 public ActionResult Edit(MemberRole memberrole)
 {
     if (ModelState.IsValid)
     {
         db.Entry(memberrole).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     return(View(memberrole));
 }
Exemplo n.º 19
0
 public InvitationDto(int id, InvitationStatus status,
                      int groupId, int fromUser, int toUser, MemberRole suggestedRole)
 {
     Id            = id;
     Status        = status;
     GroupId       = groupId;
     FromUser      = fromUser;
     ToUser        = toUser;
     SuggestedRole = suggestedRole;
 }
Exemplo n.º 20
0
        //
        // GET: /MemberRole/Delete/5

        public ActionResult Delete(Guid?id = null)
        {
            MemberRole memberrole = db.MemberRoles.Find(id);

            if (memberrole == null)
            {
                return(HttpNotFound());
            }
            return(View(memberrole));
        }
 public GroupMemberInfoView(int userId, string username, string avatarLink,
                            MemberRole memberRole, bool paid, MemberCurriculumStatus curriculumStatus)
 {
     UserId           = userId;
     Username         = username;
     AvatarLink       = avatarLink;
     MemberRole       = memberRole;
     Paid             = paid;
     CurriculumStatus = curriculumStatus;
 }
Exemplo n.º 22
0
 public Invitation(int fromUser, int toUser, int groupId, MemberRole suggestedRole, InvitationStatus status,
                   int id = 0)
 {
     Id            = id;
     SuggestedRole = suggestedRole;
     Status        = Ensure.Any.IsNotNull(status);
     GroupId       = groupId;
     FromUser      = fromUser;
     ToUser        = toUser;
 }
Exemplo n.º 23
0
 public Member(string name, string email, string password, MemberRole role)
 {
     Id = Guid.NewGuid();
     Name = name;
     _saltBytes = GenerateSalt();
     Salt = Convert.ToBase64String(_saltBytes);
     Password = HashPassword(password, _saltBytes);
     CreatedAt = DateTime.Now;
     Role = role;
     Email = email;
 }
Exemplo n.º 24
0
        public async Task <IActionResult> Create([Bind("MemberRoleId,MemberRoleName")] MemberRole memberRole)
        {
            if (ModelState.IsValid)
            {
                _context.Add(memberRole);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(memberRole));
        }
Exemplo n.º 25
0
 public bool IsPermissionGranted(MemberRole role, Permission permission, ContentThread thread = null)
 {
     if (thread == null)
     {
         return(IsPermissionGranted(role.Id, permission.Name));
     }
     else
     {
         return(IsPermissionGranted(role.Id, permission.Name, thread.Id));
     }
 }
Exemplo n.º 26
0
 public int GetUniversityById(int memberId)
 {
     using (AttenderEntities ef = new AttenderEntities())
     {
         MemberRole item = ef.MemberRoles.FirstOrDefault(a => a.MemberId == memberId);
         if (item != null)
         {
             return(item.UniversityId);
         }
     }
     return(0);
 }
Exemplo n.º 27
0
 public int GetIdByMemberId(int memberId, string role)
 {
     using (AttenderEntities ef = new AttenderEntities())
     {
         MemberRole item = ef.MemberRoles.FirstOrDefault(a => a.MemberId == memberId && a.Role == role);
         if (item != null)
         {
             return(item.Id);
         }
     }
     return(0);
 }
Exemplo n.º 28
0
 public InvitationModel(int id, int fromUser, string fromUserName, int toUser,
                        string toUserName, int toGroup, string toGroupTitle, MemberRole suggestedRole)
 {
     Id            = id;
     FromUser      = fromUser;
     FromUserName  = fromUserName;
     ToUser        = toUser;
     ToUserName    = toUserName;
     ToGroup       = toGroup;
     ToGroupTitle  = toGroupTitle;
     SuggestedRole = suggestedRole;
 }
Exemplo n.º 29
0
        public ActionResult Create(MemberRole memberrole)
        {
            if (ModelState.IsValid)
            {
                memberrole.Id = Guid.NewGuid();
                db.MemberRoles.Add(memberrole);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            return(View(memberrole));
        }
Exemplo n.º 30
0
        //OnlineShopContext context = new OnlineShopContext();
        protected override void Seed(OnlineShopContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.

            context.Role.AddOrUpdate(x => x.RoleId,
                                     new Roles()
            {
                RoleName = "Admin"
            },
                                     new Roles()
            {
                RoleName = "User"
            }
                                     );
            context.CartStatus.AddOrUpdate(x => x.CartStatusId,
                                           new CartStatus()
            {
                Cartstatus = "Added to cart"
            },
                                           new CartStatus()
            {
                Cartstatus = "Removed from cart"
            },
                                           new CartStatus()
            {
                Cartstatus = "Purchased the item"
            }
                                           );

            GenericUnitOfWork _unitOfWork = new GenericUnitOfWork();
            Member            mem         = new Member();

            mem.FirstName  = "Admin";
            mem.LastName   = "Admin";
            mem.EmailId    = "*****@*****.**";
            mem.CreatedOn  = DateTime.Now;
            mem.ModifiedOn = DateTime.Now;
            mem.Password   = EncryptDecrypt.Encrypt("abc123", true);
            mem.IsActive   = true;
            mem.IsDelete   = false;
            _unitOfWork.GetRepositoryInstance <Member>().Add(mem);

            // Adding Member Role
            MemberRole mem_Role = new MemberRole();

            mem_Role.MemberId = mem.MemberId;
            mem_Role.RoleId   = 1;
            _unitOfWork.GetRepositoryInstance <MemberRole>().Add(mem_Role);
        }
Exemplo n.º 31
0
        public TopicMember(Guid topicId, Guid userId, MemberRole role, bool suppressJoinTopicEvent = false)
        {
            Guard.Argument(() => role).Defined();

            TopicId = topicId;
            UserId  = userId;
            Role    = role;

            if (!suppressJoinTopicEvent)
            {
                PushDomainEvent(new JoinTopicEvent(topicId, userId));
            }
        }
Exemplo n.º 32
0
 public ActionResult UpdateRole(MemberRole memberrole)
 {
     if (!ModelState.IsValid)
     {
         return(RedirectToAction("Index"));
     }
     else
     {
         db.Entry(memberrole).State = System.Data.Entity.EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
 }
Exemplo n.º 33
0
 public void RemoveRole(MemberRole role)
 {
     roles.Remove(role);
 }
        public JsonResult RemoveFromRole(long MemberID, long RoleID)
        {
            Member member = Web.Admin.Logic.Collections.Members.GetBy(MemberID);
            Role role = Web.Admin.Logic.Collections.Roles.GetBy(RoleID);

            // Ignore admin in admins role
            if (member.Name.ToLower() == "admin" && role.Name.ToLower() == "admins")
            {
                AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberNoRemovedAdminFromRole, member.Name, member.Email, role.Name));
            }
            else
            {
                MemberRole memberrole = new MemberRole();
                memberrole.MemberID = MemberID;
                memberrole.RoleID = RoleID;
                memberrole.Delete();

                AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberRemovedFromRole, member.Name, member.Email, role.Name));
            }

            if (role.Name.ToLower() == "blocked")
            {
                MemberAttempt MemberAttempt = MemberAttempts.GetValid(MemberID, DateTime.Now, MemberAttemptTypes.LoginPasswordFailed);
                if (MemberAttempt.AttemptID > 0)
                {
                    MemberAttempt.Attempts = 0;
                    MemberAttempt.Save();
                }
            }

            MemberListModel model = new MemberListModel();

            model.Members.Add(member);

            return Json(new
            {
                Html = this.RenderPartialView(@"_MemberRoleList", model),
            }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult ImportMembers()
        {
            System.Threading.Thread.Sleep(200);

            CultureInfo provider = CultureInfo.InvariantCulture;
            List<Member> MemberResult = new List<Member>();
            int LineNumber = 1;

            try
            {
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    String FileContent = "";
                    HttpPostedFileBase PostedFile = Request.Files[i];

                    using (System.IO.Stream input = PostedFile.InputStream)
                    {
                        byte[] buffer = new byte[PostedFile.InputStream.Length];
                        input.Read(buffer, 0, buffer.Length);
                        FileContent = System.Text.ASCIIEncoding.UTF8.GetString(buffer);
                    }

                    if (FileContent.Length > 0)
                    {
                        string[] Lines = FileContent.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                        AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberUploadHasStarted, Lines.Length));

                        int Added = 0;
                        int Failed = 0;
                        int Exists = 0;

                        foreach (String Line in Lines)
                        {
                            System.Threading.Thread.Sleep(1);

                            if (LineNumber == 1 || Line == null || Line.Trim().Length == 0)
                            {
                                LineNumber++;
                                continue;
                            }

                            List<string> Values = new List<string>();
                            CsvParser parser = new CsvParser(Line);

                            foreach (string s in parser)
                                Values.Add(s.Trim());

                            if (Values.Count >= 11)
                            {
                                Member Member = Web.Admin.Logic.Collections.Members.GetByEmail(Values[2]);
                                if (Member.MemberID > 0)
                                {
                                    Member.UIMessage = "Member already exists.";
                                    Member.UILineNumber = LineNumber;
                                    Member.UIMessageType = Logic.UIMessageType.Warning;
                                    AuditEvent.AppEventWarning(Profile.Member.Email, String.Format(AuditEvent.MemberUploadMemberExists, Member.Name, Member.Email));
                                    Exists++;
                                }
                                else
                                {
                                    Member.Name = Values[0];
                                    Member.Email = Values[2];

                                    bool randomPassword = false;
                                    if (Values[3] == null || Values[3].Trim().Length == 0)
                                    {
                                        Member.Password = Web.Admin.Logic.StringTool.RandomString(10);
                                        randomPassword = true;
                                    }
                                    else
                                    {
                                        Member.Password = Values[3];
                                    }

                                    Member.Avatar = Values[4];

                                    if(Values[5] != null && Values[5].Length > 0)
                                    {
                                        try{

                                            if (Member.Avatar == null || Member.Avatar.Trim().Length == 0)
                                            {
                                                Member.Avatar = Web.Admin.Logic.StringTool.RandomString(24);
                                            }

                                            SaveAvatarFromBase64FromByteArray(Member.Avatar, Values[5]);

                                        }
                                        catch { Member.Avatar = ""; }
                                    }

                                    if(BuiltInRoleMember.ContainsMember(Member.Name))
                                        Member.IsBuiltIn = true;
                                    else
                                        Member.IsBuiltIn = false;

                                    try
                                    {
                                        Member.LastLogin = DateTime.ParseExact(Values[6], "dd.MM.yyyy HH:mm:ss", provider);
                                    }
                                    catch { }

                                    try
                                    {
                                        Member.Created = DateTime.ParseExact(Values[7], "dd.MM.yyyy HH:mm:ss", provider);
                                    }
                                    catch { }

                                    Member.Save();
                                    Added ++;

                                    if(Values[1] != null && Values[1].Length > 0)
                                    {
                                        string[] toRols = Values[1].Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                                        foreach (string RoleName in toRols)
                                        {
                                            Role Role = Roles.GetBy(RoleName);
                                            if (Role.RoleID > 0)
                                            {
                                                MemberRole MemberRole = new MemberRole();
                                                MemberRole.MemberID = Member.MemberID;
                                                MemberRole.RoleID = Role.RoleID;
                                                MemberRole.Save();
                                            }
                                            else
                                            {
                                                // Create new role ?

                                            }
                                        }
                                    }

                                    Member.UIMessage = "Member has been added." + (randomPassword ? " (Random password)" : "");
                                    Member.UIMessageType = Logic.UIMessageType.Success;
                                    Member.UILineNumber = LineNumber;
                                    AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberUploadedItemAdded, Member.Name, Member.Email));
                                }

                                MemberResult.Add(Member);
                                if (Values[8] != null && Values[8].Trim().Length > 0)
                                {
                                    MemberToken Token = MemberTokens.GetByMember(Member.MemberID);

                                    if (Token.MemberTokenID <= 0)
                                        Token = MemberTokens.GetByToken(Values[8].Trim());

                                    if (Token.MemberTokenID <= 0)
                                    {
                                        MemberToken MemberToken = new MemberToken();
                                        MemberToken.MemberID = Member.MemberID;
                                        MemberToken.Token = Values[8];
                                        MemberToken.GeneratedBy = Values[9];

                                        try
                                        {
                                            MemberToken.Created = DateTime.ParseExact(Values[10], "dd.MM.yyyy HH:mm:ss", provider);
                                        }
                                        catch { }

                                        try
                                        {
                                            if (Values.Count == 12)
                                                MemberToken.Modified = DateTime.ParseExact(Values[11], "dd.MM.yyyy HH:mm:ss", provider);
                                        }
                                        catch { }

                                        MemberToken.Save();
                                    }
                                    else
                                    {
                                        Member member = Web.Admin.Logic.Collections.Members.GetBy(Token.MemberID);
                                        Member.UIMessage = String.Format("Member has been added, but API token \"{0}\" already exists in database for member \"{1}\" <{2}>", Values[8], member.Name, member.Email);
                                        Member.UIMessageType = Logic.UIMessageType.Warning;
                                    }
                                }
                            }
                            else if (Values.Count > 0)
                            {
                                Member Member = new Member();

                                Member.UIMessage = "Wrong line format. Number of columns: " + Values.Count.ToString();
                                Member.UIMessageType = Logic.UIMessageType.ErrorOrDanger;
                                Member.UILineNumber = LineNumber;
                                MemberResult.Add(Member);
                                Failed++;

                                AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberUploadWrongLineFormat,LineNumber,Values.Count));
                            }

                            LineNumber++;
                        }

                        AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberUploadHasStarted, Lines.Length, Added, Exists, Failed));
                    }
                }

                System.Threading.Thread.Sleep(1000);
                MemberListModel Model = new MemberListModel();
                Model.Members = MemberResult;

                return Json(new
                {
                    NotifyType = NotifyType.Dialog,
                    Html = this.RenderPartialView(@"_ImportMembersResult", Model)

                }, "text/html", JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {

                RequestResultModel _model = new RequestResultModel();

                _model.Title = "Warning";
                _model.Message = String.Format("Something went wrong: {0}", HttpUtility.HtmlEncode(ex.Message));
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                _model.HideInSeconds = 0;
                _model.Height = 250;

                AuditEvent.AppEventError(Profile.Member.Email, _model.Message, AuditEvent.GetSessionDetails(ex.StackTrace));

                return Json(new
                {
                    Status = "Ok",
                    NotifyType = NotifyType.DialogInline,
                    Html = this.RenderPartialView(@"_RequestResultDialog", _model)

                }, "text/html", JsonRequestBehavior.AllowGet);

            }
        }
        public ActionResult AuthTwitter()
        {
            // http://stackoverflow.com/questions/3599621/is-there-a-way-to-get-an-users-email-id-after-verifying-her-twitter-identity-us
            TwitterConsumer.TwitterConsumerKey = AppSession.Parameters.SocialTwitterConsumerKey.Value;
            TwitterConsumer.TwitterConsumerSecret = AppSession.Parameters.SocialTwitterConsumerSecret.Value;

            String RedirectTo = "";

            if (TwitterConsumer.IsTwitterConsumerConfigured)
            {
                string screenName;
                int userId;
                string AccessToken;
                if (TwitterConsumer.TryFinishSignInWithTwitter(out screenName, out userId, out AccessToken))
                {
                    // In a real app, the Twitter username would likely be used
                    // to log the user into the application.
                    String memberName = String.Format("{0}@twitter.com",screenName);
                    Member member = Members.GetByEmail(memberName);

                    if (member.MemberID <= 0)
                    {
                        member.Name = screenName;
                        member.Email = memberName;
                        member.Password = StringTool.RandomString(24);
                        member.TimeZoneID = "";
                        member.Save();

                        MemberSocialNetwork memberNetwork = new MemberSocialNetwork();
                        memberNetwork.MemberID = member.MemberID;
                        memberNetwork.SocialNetworkID = 2;
                        memberNetwork.SocialNetworkUserID = userId.ToString();
                        memberNetwork.SocialNetworkUserEmail = "";
                        memberNetwork.SocialNetworkUserName = screenName;
                        memberNetwork.AccessToken = AccessToken;
                        memberNetwork.Save();

                        if (member.MemberID > 0)
                        {
                            string[] RoleNames = AppParams.SocialTwitterRoles.Value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                            foreach (String RoleName in RoleNames)
                            {
                                Role role = Web.Admin.Logic.Collections.Roles.GetBy(RoleName.Trim());
                                if (role.RoleID > 0)
                                {
                                    MemberRole memberrole = new MemberRole();
                                    memberrole.MemberID = member.MemberID;
                                    memberrole.RoleID = role.RoleID;
                                    memberrole.Save();
                                }
                            }

                        }
                    }
                    else
                    {
                        member.UpdateLoginTime();

                        MemberSocialNetwork memberNetwork = MemberSocialNetworks.GetByMemberID(member.MemberID, 2, userId.ToString());

                        memberNetwork.SocialNetworkID = 2;
                        memberNetwork.SocialNetworkUserID = userId.ToString();
                        memberNetwork.SocialNetworkUserEmail = "";
                        memberNetwork.SocialNetworkUserName = screenName;
                        memberNetwork.AccessToken = AccessToken;

                        if (memberNetwork.MemberID <= 0)
                        {
                            memberNetwork.MemberID = member.MemberID;
                            memberNetwork.Save();
                        }
                        else
                            memberNetwork.UpdateAccessToken();
                    }

                    Domain _domain = Domains.GetByName(AppSession.SignUpDomain);
                    if (_domain.DomainID > 0)
                    {
                        MemberDomain _memberDomain = new MemberDomain();
                        _memberDomain.DomainID = _domain.DomainID;
                        _memberDomain.MemberID = member.MemberID;
                        _memberDomain.Save();
                    }

                    RedirectTo = SignInMember(memberName, member, false, "", "SSI via Twitter.");
                }
                else
                {
                    return TwitterConsumer.StartSignInWithTwitter(true).AsActionResultMvc5();
                }
            }

            return new RedirectResult(RedirectTo);
        }
        public ActionResult SetMemberGroup(SetMembersGroup Info)
        {
            foreach (long itemID in Info.MemberID)
            {
                MemberRole _item = new MemberRole();
                _item.RoleID = Info.GroupID;
                _item.MemberID = itemID;
                _item.Save();

                Member Member = Web.Admin.Logic.Collections.Members.GetBy(itemID);
                Role Role = Web.Admin.Logic.Collections.Roles.GetBy(Info.GroupID);
                AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberAssigToRole, Member.Name, Member.Email, Role.Name));
            }

            return Json(new
            {
            }, JsonRequestBehavior.AllowGet);
        }
        public JsonResult AssignRolesToMember(long MemberID, long[] AssignRoles)
        {
            Member member = Web.Admin.Logic.Collections.Members.GetBy(MemberID);
            foreach (long _roleID in AssignRoles)
            {
                Role Role = Web.Admin.Logic.Collections.Roles.GetBy(_roleID);
                if (Role.RoleID > 0)
                {
                    MemberRole memberrole = new MemberRole();
                    memberrole.MemberID = MemberID;
                    memberrole.RoleID = Role.RoleID;
                    memberrole.Save();

                    AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberAssigToRole, member.Name, member.Email, Role.Name));
                }
            }

            MemberListModel model = new MemberListModel();
            model.Members.Add(member);

            return Json(new
            {
                Html = this.RenderPartialView(@"_MemberRoleList", model),
            }, JsonRequestBehavior.AllowGet);
        }
        private ActionResult AuthFacebook()
        {
            // http://developers.facebook.com/docs/reference/api/user/
            // https://developers.facebook.com/docs/howtos/login/server-side-re-auth/
            String RedirectTo = "";

            IAuthorizationState authorization = AppSession.AppFacebookClient.ProcessUserAuthorization(Request);

            if (authorization == null)
            {
                // https://developers.facebook.com/docs/reference/login/#permissions
                var scope = new List<string>();
                scope.Add("email");
                scope.Add("user_likes");
                scope.Add("read_stream");
                scope.Add("user_online_presence");
                scope.Add("read_stream");

                // Kick off authorization request
                return AppSession.AppFacebookClient.PrepareRequestUserAuthorization().AsActionResultMvc5();
            }
            else
            {
                var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken) + "&fields=id,name,first_name,last_name,username,email,gender,locale,middle_name,timezone");
                using (var response = request.GetResponse())
                {
                    using (var responseStream = response.GetResponseStream())
                    {

                        var graph = FacebookGraph.Deserialize(responseStream);
                        var name = HttpUtility.HtmlEncode(graph.Name);
                        var firstName = HttpUtility.HtmlEncode(graph.FirstName);
                        var lastName = HttpUtility.HtmlEncode(graph.LastName);

                        // to log the user into the application.
                        String memberName = String.Format("{0}.{1}@facebook.com", firstName, lastName);
                        Member member = Members.GetByEmail(memberName);
                        if (member.MemberID <= 0)
                        {
                            member.Name = String.Format("{0} {1}", firstName, lastName);
                            member.Email = memberName;
                            member.Password = StringTool.RandomString(24);
                            member.TimeZoneID = "";
                            member.Save();

                            MemberSocialNetwork memberNetwork = new MemberSocialNetwork();
                            memberNetwork.MemberID = member.MemberID;
                            memberNetwork.SocialNetworkID = 1;
                            memberNetwork.SocialNetworkUserID = graph.Id.ToString();
                            //memberNetwork.SocialNetworkUserEmail = graph.Email;
                            memberNetwork.SocialNetworkUserName = member.Name;
                            memberNetwork.AccessToken = authorization.AccessToken;
                            memberNetwork.Save();

                            if (member.MemberID > 0)
                            {
                                string[] RoleNames = AppParams.SocialFacebookRoles.Value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                                foreach (String RoleName in RoleNames)
                                {
                                    Role role = Web.Admin.Logic.Collections.Roles.GetBy(RoleName.Trim());
                                    if (role.RoleID > 0)
                                    {
                                        MemberRole memberrole = new MemberRole();
                                        memberrole.MemberID = member.MemberID;
                                        memberrole.RoleID = role.RoleID;
                                        memberrole.Save();
                                    }
                                }

                            }
                        }
                        else
                        {
                            member.UpdateLoginTime();

                            MemberSocialNetwork memberNetwork = MemberSocialNetworks.GetByMemberID(member.MemberID, 1, graph.Id.ToString());

                            memberNetwork.SocialNetworkID = 1;
                            memberNetwork.SocialNetworkUserID = graph.Id.ToString();
                            //memberNetwork.SocialNetworkUserEmail = graph.Email;
                            memberNetwork.SocialNetworkUserName = member.Name;
                            memberNetwork.AccessToken = authorization.AccessToken;

                            if (memberNetwork.MemberID <= 0)
                            {
                                memberNetwork.MemberID = member.MemberID;
                                memberNetwork.Save();
                            }
                            else
                                memberNetwork.UpdateAccessToken();
                        }

                        Domain _domain = Domains.GetByName(AppSession.SignUpDomain);
                        if (_domain.DomainID > 0)
                        {
                            MemberDomain _memberDomain = new MemberDomain();
                            _memberDomain.DomainID = _domain.DomainID;
                            _memberDomain.MemberID = member.MemberID;
                            _memberDomain.Save();
                        }

                        RedirectTo = SignInMember(memberName, member, false, "", "SSI via Facebook.");
                        return new RedirectResult(RedirectTo);
                    }
                }
            }

            // return new EmptyResult();
        }
        private ActionResult AuthYahoo()
        {
            String RedirectTo = "";
            OpenIdRelyingParty OpenID = new OpenIdRelyingParty();
            var response = OpenID.GetResponse();

            if (response == null)
            {
                //Let us submit the request to OpenID provider
                string OpenidIdentifier = "http://me.yahoo.com/";

                Identifier ID;
                if (Identifier.TryParse(OpenidIdentifier, out ID))
                {
                    var request = OpenID.CreateRequest(OpenidIdentifier);
                    var fetch = new FetchRequest();

                    fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Contact.Email, true));
                    fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Name.First, true));
                    fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Name.Middle, true));
                    fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Name.Last, true));
                    fetch.Attributes.Add(new AttributeRequest(WellKnownAttributes.Name.FullName, true));
                    request.AddExtension(fetch);

                    return request.RedirectingResponse.AsActionResultMvc5();
                }

                throw new Exception(GetLabel("Account.SignIn.InvalidID"));
            }
            else
            {
                //Let us check the response
                switch (response.Status)
                {
                    case AuthenticationStatus.Authenticated:
                        {
                            String MyOpenID = response.ClaimedIdentifier;
                            //check if user exist

                            var fetch = response.GetExtension<FetchResponse>();
                            string email = String.Empty;
                            string firstName = String.Empty;
                            string lastName = String.Empty;
                            string fullName = String.Empty;

                            if (fetch != null)
                            {
                                email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
                                firstName = fetch.GetAttributeValue(WellKnownAttributes.Name.First);
                                lastName = fetch.GetAttributeValue(WellKnownAttributes.Name.Last);
                                fullName = fetch.GetAttributeValue(WellKnownAttributes.Name.FullName);
                            }

                            // to log the user into the application.
                            String memberName = String.Format(email);
                            Member member = Members.GetByEmail(memberName);
                            if (member.MemberID <= 0)
                            {
                                string Name = String.Format("{0} {1}", firstName, lastName);
                                member.Name = Name != null && Name.Trim().Length > 0 ? Name : fullName;
                                member.Email = memberName;
                                member.Password = StringTool.RandomString(24);
                                member.TimeZoneID = "";
                                member.Save();

                                if (member.MemberID > 0)
                                {
                                    string[] RoleNames = AppParams.SocialYahooRoles.Value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                                    foreach (String RoleName in RoleNames)
                                    {
                                        Role role = Web.Admin.Logic.Collections.Roles.GetBy(RoleName.Trim());
                                        if (role.RoleID > 0)
                                        {
                                            MemberRole memberrole = new MemberRole();
                                            memberrole.MemberID = member.MemberID;
                                            memberrole.RoleID = role.RoleID;
                                            memberrole.Save();
                                        }
                                    }
                                }
                            }
                            else
                            {
                                member.UpdateLoginTime();
                            }

                            Domain _domain = Domains.GetByName(AppSession.SignUpDomain);
                            if (_domain.DomainID > 0)
                            {
                                MemberDomain _memberDomain = new MemberDomain();
                                _memberDomain.DomainID = _domain.DomainID;
                                _memberDomain.MemberID = member.MemberID;
                                _memberDomain.Save();
                            }

                            RedirectTo = SignInMember(memberName, member, false, "", "SSI via Yahoo.");
                            return new RedirectResult(RedirectTo);
                        }
                    case AuthenticationStatus.Canceled:
                        {
                            throw new Exception(GetLabel("Account.SignIn.CanceledProvider"));
                        }
                    case AuthenticationStatus.Failed:
                        {
                            throw new Exception(response.Exception.Message);
                        }
                }

            }

            return new EmptyResult();
        }
        public ActionResult Register(string Name, string Email, string Password, string Confirmation, string ReturnUrl, List<ProfileFieldInfo> FieldInfo, string RequestID, string SessionID, int TimeZoneOffset)
        {
            AppParams.RefreshAppParameters();
            string AfterSingUpRedirectUrl = "";

            if (AppSession.Parameters.RegistrationSelfRegistration.Value == "false")
            {
                if (AppSession.IsMemberInAdminRole)
                {

                }
                else
                {

                    if (ReturnUrl == null || ReturnUrl.Trim().Length == 0)
                        ReturnUrl = (ReturnUrl != null && ReturnUrl.Length > 0) ? ReturnUrl : ((AppSession.Parameters.RulesRedirectAfterLogin.Value != null && AppSession.Parameters.RulesRedirectAfterLogin.Value.Length > 0) ? AppSession.Parameters.RulesRedirectAfterLogin.Value : Url.Content("~/"));

                    AuditEvent.AppEventError(AppSession.Parameters.GeneralAdminEmail.Value, "Somebody tries to Register notification but it was switched off. ", AuditEvent.GetSessionDetails());
                    return new RedirectResult(ReturnUrl);
                }
            }

            RequestResultModel _model = new RequestResultModel();

            if (AppSession.IsEmail(Name))
            {
                _model.Message += String.Format("<li>{0}</<li>", GetLabel("Account.CreateAccount.NameLooksLikeEmail"));
            }

            if (Name == null || Name.Trim().Length == 0 ||
               ((Password == null || Password.Trim().Length == 0)) ||
               Email == null || Email.Trim().Length == 0 ||
               Password != Confirmation ||
               !AppSession.IsEmail(Email) ||
               (Password != null && Password.Length > 0 && Password.Length <=3) ||
               (Confirmation != null && Confirmation.Length > 0 && Confirmation.Length <=3))
            {
                if (Name == null || Name.Trim().Length == 0)
                    _model.Message += String.Format("<li>{0}</<li>", GetLabel("Account.CreateAccount.NameIsEmpty"));

                if ((Password == null || Password.Trim().Length == 0))
                    _model.Message += String.Format("<li>{0}</<li>", GetLabel("Account.CreateAccount.PasswordIsEmty"));

                if (Email == null || Email.Trim().Length == 0)
                    _model.Message += String.Format("<li>{0}</<li>", GetLabel("Account.CreateAccount.EmailIsEmpty"));

                if (Email != null && !AppSession.IsEmail(Email))
                    _model.Message += String.Format("<li>{0}</<li>", GetLabel("Account.CreateAccount.EmailWrongFromat"));

                if (Password != Confirmation)
                    _model.Message += String.Format("<li>{0}</<li>", GetLabel("Account.CreateAccount.PasswordNoMatch"));

                if ((Password != null && Password.Length > 0 && Password.Length < AppSession.PasswordMaxLength) ||
                (Confirmation != null && Confirmation.Length > 0 && Confirmation.Length < AppSession.PasswordMaxLength))
                {
                    _model.Message += String.Format("<li>{0}</<li>", String.Format(GetLabel("Account.CreateAccount.PasswordLength"), AppSession.PasswordMaxLength));
                }
            }

            // Check mandatory fields
            if (FieldInfo != null)
            {
                foreach (ProfileFieldInfo Field in FieldInfo)
                {
                    ProfileField profileField = ProfileFields.GetBy(int.Parse(Field.ID));
                    if (profileField.IsMandatory == 1 && (Field.Value == null || Field.Value.Trim().Length == 0))
                    {
                        _model.Message += String.Format("<li>{0}</li>", String.Format(GetLabel("Account.CreateAccount.Mandatory"), profileField.FieldName));
                    }

                    if (profileField.IsMandatory == 1 && profileField.FieldTypeID == ProfileFieldTypeEnum.CheckBox && Field.Value != null && Field.Value.ToLower() == "false")
                    {
                        _model.Message += String.Format("<li>{0}</li>", String.Format(GetLabel("Account.CreateAccount.Mandatory"), profileField.FieldName));
                    }
                }
            }

            bool nonAlphaNumeric = Name.Replace(" ", "").All(c => char.IsLetterOrDigit(c));
            if (!nonAlphaNumeric)
            {
                _model.Message += String.Format("<li>{0}</<li>", GetLabel("Account.CreateAccount.NameNonAlfaNum"));
            }

            if (_model.Message.Length > 0)
            {
                _model.Message = String.Format("<ul class=\"error-message-list\">{0}</ul>", _model.Message);
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;

                return Json(new
                {
                    Status = RequestResultInfoType.ErrorOrDanger,
                    NotifyType = NotifyType.DialogInline,
                    Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

                }, JsonRequestBehavior.AllowGet);
            }

            // Check email format
            if (!AppSession.IsEmail(Email))
            {
                _model.Title = GetLabel("Account.Controller.Warning");
                _model.Message = GetLabel("Account.Controller.WrongEmail");
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                AuditEvent.AppEventError(AppParams.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountWrongEmail, Name, Email));
            }
            else
            {
                if (!AppSession.IsMailDomainAllowed(Email))
                {
                    _model.Title = GetLabel("Account.Controller.Warning");
                    _model.Message = GetLabel("Account.Controller.DomainNotAllowed");
                    _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                    AuditEvent.AppEventError(AppParams.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountDomainNotAllowed, Name, Email));
                }
                else
                {
                    Member Member = Members.GetByEmailOrName(Email, Name);

                    if (Member.MemberID > 0)
                    {
                        _model.Title = GetLabel("Account.Controller.Warning");
                        _model.Message = GetLabel("Account.Controller.AccountExists");
                        _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                        AuditEvent.AppEventError(AppParams.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountAccountExists, Name, Email));
                    }
                    else
                    {
                        // Was account activated ?
                        // Was account blocked ?

                        Member member = new Logic.Objects.Member();
                        member.Name = Name;
                        member.Email = Email;
                        member.Password = Password;
                        member.IsBuiltIn = false;
                        member.Created = DateTime.UtcNow;

                        member.Save();

                        try
                        {
                            string ActivateToken = Web.Admin.Logic.StringTool.RandomString(20);

                            if (!SendActivationEmail(Name, Email, ActivateToken)){
                                throw new Exception("Creating an account notification e-mail has not been send!");
                            }

                            ActionToken actionToken = new ActionToken();
                            actionToken.Email = Email;
                            actionToken.Token = HttpUtility.UrlDecode(ActivateToken);
                            actionToken.ActionType = ActionTokenTypes.SelfActivation;
                            actionToken.ReturnURL = AppSession.ReturnUrl != null ? AppSession.ReturnUrl : ( AppSession.Parameters.RulesRedirectAfterLogout.Value != "" ? AppSession.Parameters.RulesRedirectAfterLogout.Value : "") ;
                            actionToken.Save();

                            if (member.MemberID > 0)
                            {
                                string[] RoleNames = AppParams.RegistrationMemberRegistrationToRoles.Value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                                foreach (String RoleName in RoleNames)
                                {
                                    Role role = Web.Admin.Logic.Collections.Roles.GetBy(RoleName.Trim());
                                    if (role.RoleID > 0)
                                    {
                                        MemberRole memberrole = new MemberRole();
                                        memberrole.MemberID = member.MemberID;
                                        memberrole.RoleID = role.RoleID;
                                        memberrole.Save();
                                    }
                                }
                            }

                            if (FieldInfo != null)
                            {
                                foreach (ProfileFieldInfo Field in FieldInfo)
                                {
                                    ProfileField profileField = ProfileFields.GetBy(int.Parse(Field.ID));

                                    MemberProfileField memberProfileField = new MemberProfileField();
                                    memberProfileField.MemberID = member.MemberID;
                                    memberProfileField.FieldID = int.Parse(Field.ID);
                                    memberProfileField.FieldValue = Field.Value;

                                    if (Field.Value == null || Field.Value.Trim().Length == 0)
                                        memberProfileField.Delete();
                                    else
                                        memberProfileField.Save();
                                }
                            }

                             Domain _domain = Domains.GetByName(AppSession.SignUpDomain);

                             if (_domain.DomainID > 0)
                              {
                                  MemberDomain _memberDomain = new MemberDomain();
                                  _memberDomain.DomainID = _domain.DomainID;
                                  _memberDomain.MemberID = member.MemberID;
                                  _memberDomain.Save();
                              }

                            if (AppSession.Parameters.RulesRedirectAfterSignUp.Value != null && AppSession.Parameters.RulesRedirectAfterSignUp.Value.Length > 0)
                                AfterSingUpRedirectUrl = AppSession.Parameters.RulesRedirectAfterSignUp.Value;

                            _model.Title = GetLabel("Account.Controller.Congrat");
                            _model.Message = GetLabel("Account.Controller.ActivationMailSent");
                            _model.InfoType = RequestResultInfoType.Success;
                            AuditEvent.AppEventSuccess(AppParams.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountActivationMailSent, Name, Email));

                        }
                        catch (Exception ex) {
                            try
                            {
                                // Try to delete member if notification was failed.
                                member.Delete();
                            }
                            catch { }

                            _model.Title = GetLabel("Account.Controller.Warning");
                            _model.Message = GetLabel("Account.Controller.CantSendNotification");
                            _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                            AuditEvent.AppEventError(Email ,"Registration: Something went wrong with e-mail notification: " + ex.Message, AuditEvent.GetSessionDetails(ex.StackTrace),true);
                        }
                    }
                }
            }

            return Json(new
               {
               Status = _model.InfoType,
               RedirectTo = AfterSingUpRedirectUrl,
               NotifyType = NotifyType.DialogInline,
               Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

               }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Activate()
        {
            if (AppSession.Parameters.RegistrationSelfActivation.Value == "false")
            {
                if (AppSession.IsMemberInAdminRole)
                {

                }
                else
                {
                    string ReturnUrl = AppSession.ReturnUrl;
                    ReturnUrl = (ReturnUrl != null && ReturnUrl.Length > 0) ? ReturnUrl : ((AppSession.Parameters.RulesRedirectAfterLogin.Value != null && AppSession.Parameters.RulesRedirectAfterLogin.Value.Length > 0) ? AppSession.Parameters.RulesRedirectAfterLogin.Value : Url.Content("~/"));

                    AuditEvent.AppEventError(AppSession.Parameters.GeneralAdminEmail.Value, "Somebody tries to activate an account but it was switched off. ", AuditEvent.GetSessionDetails());
                    return new RedirectResult(ReturnUrl);
                }
            }

            string Token = Request.QueryString["t"];
            RequestResultModel model = new RequestResultModel();

            model.Title = GetLabel("Account.Controller.Warning");
            model.Message = GetLabel("Account.Controller.WrongActiveLink");
            model.InfoType = RequestResultInfoType.Information;

            if (Token != null && Token.Length > 0)
            {
                try
                {
                    // Review activation token
                    ActionToken actionToken = ActionTokens.GetBy(Token, ActionTokenTypes.SelfActivation);
                    if (actionToken.ActionID <= 0)
                    {
                        string ReturnUrl = AppSession.ReturnUrl;
                        ReturnUrl = (ReturnUrl != null && ReturnUrl.Length > 0) ? ReturnUrl : ((AppSession.Parameters.RulesRedirectAfterLogin.Value != null && AppSession.Parameters.RulesRedirectAfterLogin.Value.Length > 0) ? AppSession.Parameters.RulesRedirectAfterLogin.Value : Url.Content("~/"));

                        AuditEvent.AppEventWarning(AppSession.Parameters.GeneralAdminEmail.Value, "Somebody tries to activate an account but token doesn't exist.", AuditEvent.GetSessionDetails());
                        return new RedirectResult(ReturnUrl);
                    }

                    if (actionToken.ReturnURL != null && actionToken.ReturnURL.Length > 0)
                        AppSession.ReturnUrl = actionToken.ReturnURL;

                    Member Member = Members.GetByEmail(actionToken.Email);
                    if (Member.MemberID > 0)
                    {
                        // Remove registration roles
                        string[] RoleNames = AppParams.RegistrationMemberRegistrationToRoles.Value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (String RoleName in RoleNames)
                        {
                            Role role = Web.Admin.Logic.Collections.Roles.GetBy(RoleName.Trim());
                            if (role.RoleID > 0)
                            {
                                MemberRole memberrole = new MemberRole();
                                memberrole.MemberID = Member.MemberID;
                                memberrole.RoleID = role.RoleID;
                                memberrole.Delete();
                            }
                        }

                        // Add activation roles
                        RoleNames = AppParams.RegistrationMemberActivationToRoles.Value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (String RoleName in RoleNames)
                        {
                            Role role = Web.Admin.Logic.Collections.Roles.GetBy(RoleName.Trim());
                            if (role.RoleID > 0)
                            {
                                MemberRole memberrole = new MemberRole();
                                memberrole.MemberID = Member.MemberID;
                                memberrole.RoleID = role.RoleID;
                                memberrole.Save();
                            }
                        }

                        string ReturnURL = actionToken.ReturnURL;
                        // AuditEvent.AppEventInfo(Member.Email, "ActionToken.ReturnURL = " + actionToken.ReturnURL + " Session back URL: " + AppSession.ReturnUrl);
                        actionToken.Delete();

                        try
                        {
                            if (!SendActivationDoneEmail(Member.Name, Member.Email, ReturnURL))
                            {
                                AuditEvent.AppEventError(Member.Email, "Activation notification e-mail has not been send!", AuditEvent.GetSessionDetails());
                            }
                        }
                        catch (Exception ex)
                        {
                            AuditEvent.AppEventError(Member.Email, "Activation: Something went wrong with e-mail notification: " + ex.Message, AuditEvent.GetSessionDetails(ex.StackTrace), true);
                        }

                        model.Title = GetLabel("Account.Controller.Congrat");
                        model.Message = GetLabel("Account.Controller.Activated").Replace("{{name}}", actionToken.Email);
                        model.InfoType = RequestResultInfoType.Success;
                        AuditEvent.AppEventSuccess(Member.Email, String.Format(AuditEvent.AccountActivated, Member.Name, Member.Email));
                    }

                }
                catch (Exception ex)
                {
                    AuditEvent.AppEventError(AppSession.Parameters.GeneralAdminEmail.Value, "Something wrong with activation: " + ex.Message, AuditEvent.GetSessionDetails(ex.StackTrace),true);
                }
            }
            else
            {
                  AuditEvent.AppEventWarning(AppSession.Parameters.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountWrongActiveLink, Token));
            }

            return View("ActivateAccount", model);
        }
Exemplo n.º 43
0
 public bool IsRole(MemberRole role)
 {
     return roles.Contains(role);
 }
        public bool Authenticate(ref String Email, String Password)
        {
            bool LDAPAuthSuccess = false;
            bool IsClassicAuth = AppSession.Parameters.LDAPUseOnly.Value == "false";
            bool IsLDAPAuth = AppSession.Parameters.LDAPEnabled.Value == "true";

            //LDAP Auth
            if (AppSession.Parameters.LDAPEnabled.Value == "true" && Email.IndexOf("@"+AppSession.Parameters.LDAPDomain.Value) > 0)
            {

                LDAPTools ldapTools = new LDAPTools();
                ldapTools.UserName = Email;
                ldapTools.Password = Password;
                ldapTools.DirectoryPath = AppSession.Parameters.LDAPPath.Value;

                if (ldapTools.Authenticate())
                {
                    LDAPAuthSuccess = true;
                    string memberName = ldapTools.MemberInfo.DisplayName;
                    string memberAllGroups = ldapTools.GetGroups();

                    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
                    // The member email will be changed because the first part of e-mail can be different with user network id.
                    ///////////////////////////////////////////////////////////////////////////////////////////////////////////
                    Email = ldapTools.MemberInfo.Email;
                    Member memberNew = Members.GetByEmail(Email);

                    if (memberNew.MemberID <= 0)
                    {
                        memberNew.Name = memberName;
                        memberNew.Email = Email;
                        memberNew.Password = StringTool.RandomString(80);
                        memberNew.IsBuiltIn = false;
                        memberNew.Created = DateTime.UtcNow;
                        memberNew.Save();

                        string Message = String.Format("LDAP member added: {0} {1}", memberName, Email);
                        AuditEvent.AppEventInfo(AppSession.Parameters.GeneralAdminEmail.Value, Message , null, true);

                        // Add signin/sign up domain.
                        Domain _domain = Domains.GetByName(AppSession.SignUpDomain);
                        if (_domain.DomainID > 0)
                        {
                            MemberDomain _memberDomain = new MemberDomain();
                            _memberDomain.DomainID = _domain.DomainID;
                            _memberDomain.MemberID = memberNew.MemberID;
                            _memberDomain.Save();
                        }

                        // Create LDAP settings roles
                        if (AppSession.Parameters.LDAPAddToRoles.Value != null && AppSession.Parameters.LDAPAddToRoles.Value.Length > 0)
                        {
                            string[] memberRoles = AppSession.Parameters.LDAPAddToRoles.Value.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
                            foreach (string memberRole in memberRoles)
                            {
                                Web.Admin.Logic.Objects.Role _role = Web.Admin.Logic.Collections.Roles.GetBy(memberRole);
                                if (_role.RoleID > 0)
                                {
                                    MemberRole _memberRole = new MemberRole();
                                    _memberRole.MemberID = memberNew.MemberID;
                                    _memberRole.RoleID = _role.RoleID;
                                    _memberRole.Save();
                                }
                            }
                        }
                    }

                    // Create LDAP specific roles
                    if (memberAllGroups != null && memberAllGroups.Length > 0 && AppSession.Parameters.LDAPAddRoleGroup.Value == "true")
                    {
                        string[] memberGroups = memberAllGroups.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (string memberGroup in memberGroups)
                        {
                            Web.Admin.Logic.Objects.Role _role = Web.Admin.Logic.Collections.Roles.GetBy(memberGroup);
                            if (_role.RoleID <= 0)
                            {
                                _role.Name = memberGroup;
                                _role.Settings = "LDAP role reflection. Keep key word: [LDAP-Auto-Role] to be synchronized.";
                                _role.BackColor = "6bbb54";
                                _role.ForeColor = "ffffff";
                                _role.Save();

                                string  Message = String.Format("LDAP role added: {0}", _role.Name);
                                AuditEvent.AppEventInfo(AppSession.Parameters.GeneralAdminEmail.Value, Message, null, true);
                            };

                            if (_role.RoleID > 0)
                            {
                                MemberRole _memberRole = new MemberRole();
                                _memberRole.MemberID = memberNew.MemberID;
                                _memberRole.RoleID = _role.RoleID;
                                _memberRole.Save();
                            }
                        }
                    }

                    // Synchronize members roles with LDAP [LDAP-Auto-Role] key words.
                    List<Role> _roles = Web.Admin.Logic.Collections.Roles.GetByMemberKeyWordInDescription(memberNew.MemberID, "[LDAP-Auto-Role]");
                    string[] _groups = memberAllGroups.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                    foreach (Web.Admin.Logic.Objects.Role _role in _roles)
                    {
                        if (_groups != null && _groups.Length > 0)
                        {
                            if (_groups.Where(t => t.Trim().ToLower() == _role.Name.Trim().ToLower()).FirstOrDefault() == default(String))
                            {
                                Web.Admin.Logic.Objects.Role removeRoleFromUser = Web.Admin.Logic.Collections.Roles.GetBy(_role.Name);
                                MemberRole _memberRole = new MemberRole();
                                _memberRole.MemberID = memberNew.MemberID;
                                _memberRole.RoleID = removeRoleFromUser.RoleID;
                                _memberRole.Delete();
                            }
                        }
                        else
                        {
                            MemberRole _memberRole = new MemberRole();
                            _memberRole.MemberID = memberNew.MemberID;
                            _memberRole.RoleID = _role.RoleID;
                            _memberRole.Delete();

                        }
                    }
                }
            }

            //Classic Auth
            Member member = Members.GetByEmail(Email);
            if (member.MemberID > 0)
            {
                if ( (IsLDAPAuth && LDAPAuthSuccess) ||
                     (IsClassicAuth && Member.ComputePasswordHash(Password) == member.Password)
                   )
                {
                    MemberAttempt Attempt = MemberAttempts.GetTodayLoginPasswordFail(member.MemberID);
                    if (Attempt.AttemptID > 0)
                    {
                        Attempt.IsAttemptValid = 0;
                        Attempt.Save();
                    }

                    // Add signin/sign up domain.
                    Domain _domain = Domains.GetByName(AppSession.SignUpDomain);
                    if (_domain.DomainID > 0)
                    {
                        MemberDomain _memberDomain = new MemberDomain();
                        _memberDomain.DomainID = _domain.DomainID;
                        _memberDomain.MemberID = member.MemberID;
                        _memberDomain.Save();
                    }

                    member.UpdateLoginTime();

                    return true;
                }
                else
                {
                    MemberAttempt Attempt = MemberAttempts.GetTodayLoginPasswordFail(member.MemberID);

                    if (Attempt.MemberID <= 0)
                    {
                        Attempt.MemberID = member.MemberID;
                        Attempt.AttemptType = MemberAttemptTypes.LoginPasswordFailed;
                        Attempt.IsAttemptValid = 1;
                    }

                    if (Attempt.Attempts > 0)
                        Attempt.Attempts++;
                    else
                        Attempt.Attempts = 1;

                    Attempt.Save();

                    if (AppSession.Parameters.RulesPasswordFailedRoles.Value != null && AppSession.Parameters.RulesPasswordFailedRoles.Value.Length > 0 && !AppSession.IsMemberInAdminRole)
                    {
                        Parameter Param = AppSession.Parameters.RulesPasswordFailedAttempts;

                        long value = -1;
                        bool result = long.TryParse(Param.Value, out value);

                        if (result && value > 0 && Attempt.Attempts >= value)
                        {
                            string[] RoleNames = AppSession.Parameters.RulesPasswordFailedRoles.Value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                            foreach (String RoleName in RoleNames)
                            {
                                Role role = Web.Admin.Logic.Collections.Roles.GetBy(RoleName);
                                if (role.RoleID > 0)
                                {
                                    MemberRole memberrole = new MemberRole();
                                    memberrole.MemberID = member.MemberID;
                                    memberrole.RoleID = role.RoleID;
                                    memberrole.Save();
                                }
                            }
                        }

                    }

                    return false;
                }
            }
            else
                return false;
        }
        public JsonResult AssignRoleMembers(long RoleID, int[] AssignMembers, bool Assign)
        {
            MemberListModel _model = new MemberListModel();

            foreach (int MemberID in AssignMembers)
            {
                Web.Admin.Logic.Objects.Member Member = Web.Admin.Logic.Collections.Members.GetBy(MemberID);
                Web.Admin.Logic.Objects.Role Role = Web.Admin.Logic.Collections.Roles.GetBy(RoleID);

                if (RoleID > 0)
                {
                    if (Member.IsBuiltIn)
                    {
                        if (Member.Name.Trim().ToLower() == "admin" && Role.Name.Trim().ToLower() == "admins")
                        {
                            AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberNoRemovedAdminFromRole, Member.Name, Member.Email, Role.Name));
                            continue;
                        }
                    }
                    else
                    {
                        MemberRole _roleMember = new MemberRole();
                        _roleMember.MemberID = MemberID;
                        _roleMember.RoleID = RoleID;

                        if (Role.Name.ToLower() == "blocked")
                            ResetPasswordfailedAttemps(MemberID);

                        if (Assign)
                        {
                            _roleMember.Save();
                            AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberAssigToRole, Member.Name, Member.Email, Role.Name));
                        }
                        else
                        {
                            _roleMember.Delete();
                            AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberRemovedFromRole, Member.Name, Member.Email, Role.Name));
                        }
                    }
                }
                else if (!Assign)
                {
                    if (Member.IsBuiltIn)
                    {
                        AuditEvent.AppEventWarning(Profile.Member.Email, String.Format(AuditEvent.MemberNoRemovedAdminFromRole, Member.Name, Member.Email, Role.Name));
                        continue;
                    }
                    else
                    {
                        MemberRole _roleMember = new MemberRole();
                        _roleMember.MemberID = MemberID;
                        _roleMember.DeleteAll();

                        ResetPasswordfailedAttemps(MemberID);
                        AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberRemovedFromAllRole, Member.Name, Member.Email));
                    }
                }
            }

            _model.Role = Roles.GetBy(RoleID);

            return Json(new
            {
                Html = ""

            }, JsonRequestBehavior.AllowGet);
        }