public string UpdateUser(int userId = -1, string propertyId = null, string propertyValue = null, string token = null, string qqfile = null)
        {
            if (Request.RequestType.Equals("OPTIONS", StringComparison.InvariantCultureIgnoreCase))
            {
                return null;
            }
            try
            {
                int authUserId = -1;
                if (token != null)
                {
                    authUserId = authenticationEngine.authenticate(token);
                }
                else
                {
                    return AddErrorHeader("An authentication token must be passed in",2);
                }
                if (authUserId < 0)
                {
                    return AddErrorHeader("You are not authenticated, please log in!", 2);
                }
                User user = userManager.GetUser(userId);
                if (user == null)
                {
                    return AddErrorHeader("User not found", 1);
                }
                if (userId == authUserId)
                {
                    System.Reflection.PropertyInfo pi = null;
                    if (propertyId != null)
                    {
                        if (propertyId == "coverPicture")
                        {
                            propertyId = "aboutPicture";//Its called a coverPicture on the site, but an aboutPicture in the database
                        }
                        pi = user.GetType().GetProperty(propertyId);
                    }
                    else
                    {
                        AddErrorHeader("You must pass in a propertyId to set", 1);
                    }

                    if (pi == null)
                    {
                        return AddErrorHeader("Invalid propertyId", 1);
                    }
                    else
                    {
                        try
                        {
                            if (propertyValue != null)
                            {
                                propertyValue = StripNewLineAndReplaceWithLineBreaks(propertyValue);
                            }
                            else if (propertyId == "profilePicture" || propertyId == "aboutPicture" || propertyId == "resume")
                            {
                                //its OK for propertyValue to be null
                            }
                            else
                            {
                                return AddErrorHeader("You must pass in a propertyValue to set", 1);
                            }
                            bool postedFile = false;
                            if (qqfile != null || Request.Files.Count == 1)
                            {
                                postedFile = true;
                            }
                            if (postedFile)
                            {
                                if (propertyId == "aboutPicture")
                                {
                                    var length = Request.ContentLength;
                                    var bytes = new byte[length];
                                    Request.InputStream.Read(bytes, 0, length);
                                    Stream s = new MemoryStream(bytes);
                                    string returnPic = userManager.UploadUserPicture(user, s, "About");
                                    return AddSuccessHeader("http://vestnstaging.blob.core.windows.net/thumbnails/" + returnPic, true);
                                }
                                else if (propertyId == "profilePicture")
                                {
                                    var length = Request.ContentLength;
                                    var bytes = new byte[length];
                                    Request.InputStream.Read(bytes, 0, length);
                                    Stream s = new MemoryStream(bytes);
                                    if (user.profilePicture != null && user.profilePictureThumbnail != null)
                                    {
                                        userManager.DeleteProfilePicture(user);
                                    }
                                    string returnPic = userManager.UploadUserPicture(user, s, "Profile");
                                    return AddSuccessHeader("http://vestnstaging.blob.core.windows.net/thumbnails/" + returnPic, true);
                                }
                                else if (propertyId == "resume")
                                {
                                    string fileName = null;
                                    if (qqfile == null)
                                    {
                                        fileName = Request.Files.Get(0).FileName;
                                    }
                                    else
                                    {
                                        fileName = qqfile;
                                    }
                                    var length = Request.ContentLength;
                                    var bytes = new byte[length];
                                    Request.InputStream.Read(bytes, 0, length);
                                    Stream fs = new MemoryStream(bytes);
                                    string[] s2 = fileName.Split('.');
                                    string fileType = s2[s2.Count() - 1].ToLower();

                                    string resumeUri = null;
                                    if (String.Compare(fileType, "pdf", true) == 0)
                                    {
                                        resumeUri = userManager.UploadResumePDF(user, fs);
                                        return AddSuccessHeader(resumeUri, true);
                                    }
                                    else if (String.Compare(fileType, "doc", true) == 0)
                                    {
                                        resumeUri = userManager.UploadResumeDoc(user, fs);
                                        return AddSuccessHeader("http://vestnstaging.blob.core.windows.net/pdfs/" + resumeUri, true);
                                    }
                                    else if (String.Compare(fileType, "docx", true) == 0)
                                    {
                                        resumeUri = userManager.UploadResumeDocx(user, fs);
                                        return AddSuccessHeader("http://vestnstaging.blob.core.windows.net/pdfs/" + resumeUri, true);
                                    }
                                    else if (String.Compare(fileType, "rtf", true) == 0)
                                    {
                                        resumeUri = userManager.UploadResumeRTF(user, fs);
                                        return AddSuccessHeader("http://vestnstaging.blob.core.windows.net/pdfs/" + resumeUri, true);
                                    }
                                    else if (String.Compare(fileType, "txt", true) == 0)
                                    {
                                        resumeUri = userManager.UploadResumeTXT(user, fs);
                                        return AddSuccessHeader("http://vestnstaging.blob.core.windows.net/pdfs/" + resumeUri, true);
                                    }
                                    else
                                    {
                                        return AddErrorHeader("Document Type not supported", 1);
                                    }
                                }
                            }
                            switch (propertyId)
                            {
                                case "profileURL":
                                    if (user.profileURL != propertyValue)
                                    {
                                        if (ValidationEngine.ValidateProfileURL(propertyValue) == ValidationEngine.Success)
                                        {
                                            pi.SetValue(user, Convert.ChangeType(propertyValue, pi.PropertyType), null);
                                        }
                                        else
                                        {
                                            return AddErrorHeader("profileURL not valid, user not updated", 1);
                                        }
                                    }
                                    else
                                    {
                                        return AddErrorHeader("profileURL already in use, user not updated", 1);
                                    }
                                    break;
                                case "school":
                                    if (ValidationEngine.ValidateSchool(propertyValue) == ValidationEngine.Success)
                                    {
                                        pi.SetValue(user, Convert.ChangeType(propertyValue, pi.PropertyType), null);
                                    }
                                    else
                                    {
                                        return AddErrorHeader("school not valid, user not updated", 1);
                                    }
                                    break;
                                case "email":
                                    if (propertyValue != user.email)
                                    {
                                        if (ValidationEngine.ValidateEmail(propertyValue) == ValidationEngine.Success && ValidationEngine.IsDuplicateEmail(propertyValue) == false)
                                        {
                                            pi.SetValue(user, Convert.ChangeType(propertyValue, pi.PropertyType), null);
                                        }
                                        else
                                        {
                                            return AddErrorHeader("email not valid, user not updated", 1);
                                        }
                                    }
                                    else
                                    {
                                        return AddErrorHeader("email match, user not updated", 1);
                                    }
                                    break;
                                case "location":
                                    if (ValidationEngine.ValidateLocation(propertyValue) == ValidationEngine.Success)
                                    {
                                        pi.SetValue(user, Convert.ChangeType(propertyValue, pi.PropertyType), null);
                                    }
                                    else
                                    {
                                        return AddErrorHeader("location not valid, user not updated", 1);
                                    }
                                    break;
                                case "firstName":
                                    if (ValidationEngine.ValidateFirstName(propertyValue) == ValidationEngine.Success)
                                    {
                                        pi.SetValue(user, Convert.ChangeType(propertyValue, pi.PropertyType), null);
                                    }
                                    else
                                    {
                                        return AddErrorHeader("firstName not valid, user not updated", 1);
                                    }
                                    break;
                                case "lastName":
                                    if (ValidationEngine.ValidateLastName(propertyValue) == ValidationEngine.Success)
                                    {
                                        pi.SetValue(user, Convert.ChangeType(propertyValue, pi.PropertyType), null);
                                    }
                                    else
                                    {
                                        return AddErrorHeader("lastName not valid, user not updated", 1);
                                    }
                                    break;
                                case "title":
                                    if (ValidationEngine.ValidateTitle(propertyValue) == ValidationEngine.Success)
                                    {
                                        pi.SetValue(user, Convert.ChangeType(propertyValue, pi.PropertyType), null);
                                    }
                                    else
                                    {
                                        return AddErrorHeader("title not valid, user not updated", 1);
                                    }
                                    break;
                                case "major":
                                    if (ValidationEngine.ValidateMajor(propertyValue) == ValidationEngine.Success)
                                    {
                                        pi.SetValue(user, Convert.ChangeType(propertyValue, pi.PropertyType), null);
                                    }
                                    else
                                    {
                                        return AddErrorHeader("major not valid, user not updated", 1);
                                    }
                                    break;
                                case "connections":
                                    if (ValidationEngine.ValidateMajor(propertyValue) == ValidationEngine.Success)
                                    {
                                        pi.SetValue(user, Convert.ChangeType(propertyValue, pi.PropertyType), null);
                                    }
                                    else
                                    {
                                        return AddErrorHeader("connections not valid, user not updated", 1);
                                    }
                                    break;
                                case "description":
                                    if (ValidationEngine.ValidateDescription(propertyValue) == ValidationEngine.Success)
                                    {
                                        pi.SetValue(user, Convert.ChangeType(propertyValue, pi.PropertyType), null);
                                    }
                                    else
                                    {
                                        return AddErrorHeader("description not valid, user not updated", 1);
                                    }
                                    break;
                                case "tagLine":
                                    if (ValidationEngine.ValidateDescription(propertyValue) == ValidationEngine.Success)
                                    {
                                        pi.SetValue(user, Convert.ChangeType(propertyValue, pi.PropertyType), null);
                                    }
                                    else
                                    {
                                        return AddErrorHeader("tagLine not valid, user not updated", 1);
                                    }
                                    break;

                            }
                            //persist user model to DB with manager updateUser method
                            user = userManager.UpdateUser(user);
                            AnalyticsAccessor aa = new AnalyticsAccessor();
                            aa.CreateAnalytic("User Update", DateTime.Now, user.userName, "Information updated: " + pi.PropertyType.ToString());

                            return AddSuccessHeader("UserId:"+userId+" successfully updated", true);
                        }
                        catch (Exception exc)
                        {
                            logAccessor.CreateLog(DateTime.Now, this.GetType().ToString() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), exc.ToString());
                            return AddErrorHeader("Something went wrong while updating this user", 1);
                        }
                    }
                }
                else
                {
                    return AddErrorHeader("User not authorized to edit this user", 3);
                }
            }
            catch (Exception ex)
            {
                logAccessor.CreateLog(DateTime.Now, this.GetType().ToString() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), ex.ToString());
                return AddErrorHeader("Something went wrong while updating this user", 1);
            }
        }
        public JsonResult MakeProfilePublic()
        {
            try
            {
                User user = userManager.GetUser(User.Identity.Name);

                if (user.isPublic == 1)
                {
                    return Json(new { MadePublicStatus = "profileAlreadyPublic" });
                }

                //ADDS TAGS
                /*
                TagManager tagManager = new TagManager();

                string lines = (Resource.freelancer_tags);
                char[] separators = { '\n', '\r' };
                var etfs = lines.Split(separators, StringSplitOptions.RemoveEmptyEntries);
                int x = 0;
                do
                {
                    if (x == etfs.Length)
                    {
                        break;
                    }
                    if (etfs[x].Substring(0, 1) == "~")
                    {
                        sTag top = tagManager.CreateSTag(0, etfs[x].Substring(1, etfs[x].Length - 1).Trim());
                        x++;
                        if (x == etfs.Length)
                        {
                            break;
                        }
                        while (etfs[x] != "!")
                        {
                            int i = etfs[x].IndexOf("(");
                            string value = etfs[x].Substring(0, i - 2);
                            sTag mid = tagManager.CreateSTag(tagManager.GetSTag(top.value).id, value);
                            x++;
                            if (x == etfs.Length)
                            {
                                break;
                            }
                        }
                    }
                    if (x == etfs.Length)
                    {
                        break;
                    }
                    else if (etfs[x].Substring(0, 1) == "!")
                    {
                        x++;
                        if (x == etfs.Length)
                        {
                            break;
                        }
                    }
                }
                while (x < etfs.Length);
                */
                //END ADD TAGS

                user = userManager.MakePublic(user, 1);
                AnalyticsAccessor aa = new AnalyticsAccessor();
                aa.CreateAnalytic("Profile Made Public", DateTime.Now, user.userName);

                if (user.isPublic == 1)
                {
                    return Json(new { MadePublicStatus = "profileMadePublic" });
                }
                else
                {
                    if (user.emailVerified == 1)
                    {
                        return Json(new { MadePublicStatus = "profileNotMadePublic" });
                    }
                    else
                    {
                        return Json(new { MadePublicStatus = "userEmailNotVerified" });
                    }
                }
            }
            catch (Exception ex)
            {
                logAccessor.CreateLog(DateTime.Now, this.GetType().ToString() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), ex.ToString());
                return Json(new { Error = "An unknown error occured" });
            }
        }
        public ActionResult Profile(string profileURL)
        {
            if (profileURL == "")
            {
                User currentUser = userManager.GetUser(User.Identity.Name);
                return RedirectToAction("Profile", "User", new { profileURL = currentUser.profileURL });
            }

            //throw (new ArgumentNullException());
            TempData["MessageBar"] = TempData["MessageBar"];
            TempData["Popup"] = TempData["Popup"];

            try
            {
                ViewBag.DisplayPicture = false;
                ViewBag.DisplayInfo = false;

                TagManager tagManager = new TagManager();

                User user = userManager.GetUserByProfileURL(profileURL);
                if (user == null)
                {
                    try
                    {
                        string userNameLoggedIn = User.Identity.Name;
                        if (userNameLoggedIn == null || userNameLoggedIn == "")
                        {
                            return RedirectToAction("Index", "Home");
                        }
                        else
                        {
                            user = userManager.GetUser(userNameLoggedIn);
                        }
                    }
                    catch (Exception e)
                    {

                    }
                }
                else if ((User.Identity.Name != user.userName) && (user.isPublic != 1))
                {
                    //if not the owner and trying to access a user that is not public
                    return RedirectToAction("Index", "Home");
                }
                //else...
                //projectManager.moveProjectRight(user, 2);
                //userManager.UpdateUser(user);
                if (user.projectOrder == null)
                {
                    userManager.ResetProjectOrder(user);
                    userManager.UpdateUser(user);
                    foreach (Project p in user.projects)
                    {
                        projectManager.resetProjectElementOrder(p);
                        projectManager.UpdateProject(p);
                    }
                }

                ProfileModel model = new ProfileModel(user);
                List<string> tagValues = new List<string>();
                //Put user's tags on the ProfileModel
                /*
                if (user.tagIds != null && user.tagIds != "")
                {
                    List<Tag> tagList = tagManager.GetTags(user.tagIds);
                    foreach (Tag tag in tagList)
                    {
                        tagValues.Add(tag.value);
                    }
                    model.tagValues = tagValues;
                }*/

                //ViewBag.WillingToRelocate = new List<string>(Enum.GetNames(typeof(WillingToRelocateType)));

                if (user.userName == User.Identity.Name && User.Identity.IsAuthenticated)
                {
                    AnalyticsAccessor aa = new AnalyticsAccessor();
                    aa.CreateAnalytic("Profile Page Hit: Logged in", DateTime.Now, user.userName);

                    //User is going to their own profile
                    ViewBag.IsOwner = true;
                    model.connections = new List<User>();
                    if (user.connections != null)
                    {
                        foreach (string userId in user.connections.Split(','))
                        {
                            if (userId.Trim() != "")
                            {
                                int userIdInt = Convert.ToInt32(userId);
                                User connection = userManager.GetUser(userIdInt);
                                model.connections.Add(connection);
                            }
                        }
                    }

                    /*//depreciated. can't use .CompleteProfilePrompt any more. will have to deal with tags some other way
                     * if (userManager.IsProfilePartiallyComplete(user))
                    {
                        //User has already entered some extra information on their profile
                        ViewBag.CompleteProfilePrompt = false;
                    }
                    else
                    {
                        //User has not updated any further info on their profile
                        //Get list of tags for picking out which ones we initially want on our profile
                        List<string> listOfLowestLevelTags = userManager.GetAllLowestLevelTagValues();
                        ViewBag.LowestLevelTags = listOfLowestLevelTags;
                        ViewBag.CompleteProfilePrompt = true;
                    }*/
                }
                else
                {
                    AnalyticsAccessor aa = new AnalyticsAccessor();
                    aa.CreateAnalytic("Profile Page Hit: Not Logged in", DateTime.Now, user.userName);

                    //User is visiting someone else's profile
                    ViewBag.IsOwner = false;
                }

                //------------------------------------------------------------
                return View(model);
            }
            catch (Exception ex)
            {
                logAccessor.CreateLog(DateTime.Now, this.GetType().ToString() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), ex.ToString());
                return View("Error");
            }
        }
        public string LogOn(string username, string password)
        {
            if (Request.RequestType.Equals("OPTIONS", StringComparison.InvariantCultureIgnoreCase))  //This is a preflight request
            {
                return null;
            }
            else
            {
                try
                {
                    User user = userManager.GetUser(username);
                    //MembershipUser mu = Membership.GetUser(username);
                    //mu.UnlockUser();
                    //mu.ChangePassword(mu.ResetPassword(), "Mpos104*");
                    if (user == null)
                    {
                        user = userManager.GetUserByEmail(username);
                        if (user != null)
                        {
                            username = user.userName;
                        }
                        else
                        {
                            return AddErrorHeader("The username/email does not exist in the database", 1);
                        }
                    }
                    if (userManager.ValidateUser(user, password))
                    {
                        AuthenticaitonEngine authEngine = new AuthenticaitonEngine();
                        string token = authEngine.logIn(user.id, user.userName);

                        AnalyticsAccessor aa = new AnalyticsAccessor();
                        aa.CreateAnalytic("User Login", DateTime.Now, user.userName);

                        JsonModels.LogOnModel logOnReturnObject = new JsonModels.LogOnModel();
                        logOnReturnObject.userId = user.id;
                        logOnReturnObject.firstName = (user.firstName != null) ? user.firstName : null;
                        logOnReturnObject.lastName = (user.lastName != null) ? user.lastName : null;
                        logOnReturnObject.profileURL = (user.profileURL != null) ? user.profileURL : null;
                        logOnReturnObject.token = token;
                        logOnReturnObject.emailVerified = (user.emailVerified == 1) ? true : false;

                        return AddSuccessHeader(Serialize(logOnReturnObject));
                    }
                    else
                    {
                        return AddErrorHeader("User Information Not Valid", 2);
                    }
                }
                catch (Exception ex)
                {
                    logAccessor.CreateLog(DateTime.Now, this.GetType().ToString() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), ex.ToString());
                    return AddErrorHeader("Something went wrong while trying to log this user in", 1);
                }
            }
        }
        public JsonResult LogOnOld(string username, string password, Boolean rememberme)
        {
            try
            {

                User user = userManager.GetUser(username);
                if (user == null)
                {
                    user = userManager.GetUserByEmail(username);
                    if (user != null)
                    {
                        username = user.userName;
                    }
                }

                if (userManager.ValidateUser(user, password))
                {
                    FormsAuthentication.SetAuthCookie(username, rememberme);

                    //fixing issue with remember me checkbox.

                    FormsAuthentication.Initialize();
                    FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, user.userName, DateTime.Now,
                      DateTime.Now.AddMinutes(30), rememberme, FormsAuthentication.FormsCookiePath);
                    HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(tkt));
                    ck.Path = FormsAuthentication.FormsCookiePath;

                    if (rememberme)
                        ck.Expires = DateTime.Now.AddMonths(1);

                    Response.Cookies.Add(ck);

                    //----------------------------------------

                    AnalyticsAccessor aa = new AnalyticsAccessor();
                    aa.CreateAnalytic("User Login", DateTime.Now, user.userName);

                    return Json(new { LogOnResult = "Success" });
                    // return Json(new { LogInStatus = "Login Success" });
                }
                else
                {
                    return Json(new { Error = "User Information Not Valid" });
                }

            }
            catch (Exception ex)
            {
                logAccessor.CreateLog(DateTime.Now, this.GetType().ToString() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), ex.ToString());
                return Json(new { Error = "An unknown error occured" });
            }
        }
Пример #6
0
        public string AddVideoElement(string ProjectID, string status, string id)
        {
            try
            {
                User user = userManager.GetUser(User.Identity.Name);

                if (!projectManager.IsUserOwnerOfProject(Int32.Parse(ProjectID), user))
                {
                    //return Json(new { Error = "Can't add video at this time" });
                    return AddErrorHeader("Can't add video at this time", 1);
                }

                int nProjectID = Convert.ToInt32(ProjectID);

                int nStatus = Convert.ToInt32(status);

                string videoID = id;
                ViewBag.VideoID = id;

                JsonModels.Artifact response = projectManager.AddVideoElement(nProjectID, "Description goes here", videoID, "unknown");
                AnalyticsAccessor aa = new AnalyticsAccessor();
                aa.CreateAnalytic("Add Media", DateTime.Now, user.userName, "Video file");

                string returnVal;
                try
                {
                    returnVal = Serialize(response);
                }
                catch (Exception exception)
                {
                    return AddErrorHeader(exception.Message, 1);
                }
                return AddSuccessHeader(returnVal);
            }
            catch (Exception ex)
            {
                logAccessor.CreateLog(DateTime.Now, this.GetType().ToString() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), ex.ToString());
                return AddErrorHeader("Error occured uploading your video", 1);
            }
        }
Пример #7
0
 public string CompleteTodo(string token)
 {
     if (Request.RequestType.Equals("OPTIONS", StringComparison.InvariantCultureIgnoreCase))  //This is a preflight request
     {
         return null;
     }
     try
     {
         int userId = authenticationEngine.authenticate(token);
         if (userId < 0)
         {
             return AddErrorHeader("Not Authenticated", 2);
         }
         bool success = userManager.CompleteTodo(userId);
         if (success)
         {
             User user = userManager.GetUser(userId);
             AnalyticsAccessor aa = new AnalyticsAccessor();
             aa.CreateAnalytic("CompleteTodo", DateTime.Now, user.userName);
             return AddSuccessHeader("ToDo Completed", true);
         }
         else
         {
             return AddErrorHeader("An error occurred while updating the user" , 1);
         }
     }
     catch (Exception ex)
     {
         return AddErrorHeader("something went wrong while updating this user's todo list status" , 1);
     }
 }
Пример #8
0
        public string VerifyEmail(string email, string hash)
        {
            if (Request.RequestType.Equals("OPTIONS", StringComparison.InvariantCultureIgnoreCase))
            {
                return null;
            }
            try
            {
                User u = userManager.GetUserByEmail(email);
                if (u != null)
                {
                    //User Manager Verify Email (email, hash)
                    if (u.verifyEmailHash == hash)
                    {
                        bool success = userManager.verifyEmail(u);
                        if (success)
                        {
                            AuthenticaitonEngine authEngine = new AuthenticaitonEngine();
                            string token = authEngine.logIn(u.id, u.userName);
                            JsonModels.RegisterResponse rr = new JsonModels.RegisterResponse();
                            rr.userId = u.id;
                            rr.token = token;

                            AnalyticsAccessor aa = new AnalyticsAccessor();
                            aa.CreateAnalytic("EmailVerified", DateTime.Now, u.userName);

                            return AddSuccessHeader(Serialize(rr));
                        }
                        else
                        {
                            return AddErrorHeader("Error updating user",1);
                        }
                    }
                    else
                    {
                        return AddErrorHeader("Invalid verify email identifier", 1);
                    }
                }
                else
                {
                    return AddErrorHeader("Invalid Email", 1);
                }
            }
            catch (Exception ex)
            {
                return AddErrorHeader("Something went wrong while verifying this email", 1);
            }
        }
Пример #9
0
        public string Register(string email, string password, string networkJoinCode = null, string firstName = null, string lastName = null, string type = "standard")
        {
            if (Request != null)
            {
                if (Request.RequestType.Equals("OPTIONS", StringComparison.InvariantCultureIgnoreCase))
                {
                    return null;
                }
            }
            try
            {
                CommunicationManager communicationManager = new CommunicationManager();
                string userName = email.Substring(0, email.IndexOf('@'));
                userName = userName.Replace("+", "");
                userName = userName.Replace(".", "");
                RegisterModel model = new RegisterModel { Email = email, UserName = userName, Password = password, ConfirmPassword = password };
                if (ValidationEngine.ValidateEmail(model.Email) != ValidationEngine.Success)
                {
                    return AddErrorHeader("Invalid Email", 1);
                }
                if (!userManager.CheckDuplicateEmail(model.Email))
                {
                    return AddErrorHeader("A user with that email already exists in our database", 1);
                }
                if (ValidationEngine.ValidateUsername(model.UserName) != ValidationEngine.Success)
                {
                    return AddErrorHeader(ValidationEngine.ValidateUsername(model.UserName), 1);
                }
                if (!userManager.CheckDuplicateUsername(model.UserName))
                {
                    return AddErrorHeader("A user with that username already exists in our database", 1);
                }
                if (ValidationEngine.ValidatePassword(model.Password) != ValidationEngine.Success)
                {
                    return AddErrorHeader(ValidationEngine.ValidateUsername(model.Password), 1);
                }
                if (model.Password != model.ConfirmPassword)
                {
                    return AddErrorHeader("Password fields do not match", 1);
                }
                if (ModelState.IsValid)
                {
                    User newUser = model.toUser();
                    newUser.profileURL = newUser.userName;
                    newUser.firstName = firstName;
                    newUser.lastName = lastName;
                    if (networkJoinCode != null)
                    {
                        NetworkManager nm = new NetworkManager();
                        Network network = nm.GetNetworkByIdentifier(networkJoinCode);
                        if (network != null)
                        {
                            newUser.title = "student";
                            newUser.organization = network.name;
                        }
                    }
                    newUser = userManager.CreateUser(newUser, model.Password);

                    UserAgreementAccessor uaa = new UserAgreementAccessor();
                    if (Request.ServerVariables["REMOTE_ADDR"] != null)
                    {
                        uaa.CreateAgreement(DateTime.Now, newUser.userName, "Agree", Request.ServerVariables["REMOTE_ADDR"]);
                    }
                    else
                    {
                        uaa.CreateAgreement(DateTime.Now, newUser.userName, "Agree", "IP not detectable");
                    }

                    userManager.ActivateUser(newUser, true);
                    //communicationManager.SendVerificationMail(userManager.GetProviderUserKey(newUser), newUser.userName, newUser.email);

                    if (networkJoinCode != null)
                    {
                        NetworkManager nm = new NetworkManager();
                        Network network = nm.GetNetworkByIdentifier(networkJoinCode);
                        if (network != null)
                        {
                            if (type == "network")
                            {
                                nm.AddNetworkAdmin(network.id, email);
                            }
                            else
                            {
                                string[] emailArray = { email };
                                nm.AddNetworkUsers(network, emailArray);
                            }
                        }
                    }
                    userManager.SendVerifyEmail(email);
                    AnalyticsAccessor aa = new AnalyticsAccessor();
                    aa.CreateAnalytic("Register", DateTime.Now, newUser.userName);
                    AuthenticaitonEngine authEngine = new AuthenticaitonEngine();
                    string token = authEngine.logIn(newUser.id, newUser.userName);
                    JsonModels.RegisterResponse rr = new JsonModels.RegisterResponse();
                    rr.userId = newUser.id;
                    rr.token = token;
                    return AddSuccessHeader(Serialize(rr));
                }
                else
                {
                    return AddErrorHeader("User Model Not Valid", 1);
                }
            }
            catch (Exception ex)
            {
                logAccessor.CreateLog(DateTime.Now, this.GetType().ToString() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), ex.ToString());
                return AddErrorHeader("Something went wrong while creating this user", 1);
            }
        }
Пример #10
0
 protected string AddErrorHeader(string message, int code)
 {
     AnalyticsAccessor aa = new AnalyticsAccessor();
     aa.CreateAnalytic("Error_Returned", DateTime.Now, "user", message);
     return "{\"Error\":{\"Code\":"  + @code.ToString() + ",\"Message\": \"" + @message + "\"},\"Success\": false,\"Reponse\":null}";
 }