protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (!IsValid)
            {
                feedbackPanel.Visible = true;
                lblError.Text         = "Invalide registratie!";
                lblError.CssClass     = "text-danger";
                return;
            }

            if (StartDate.SelectedDate == DateTime.Parse("1-1-0001") ||
                EndDate.SelectedDate == DateTime.Parse("1-1-0001"))
            {
                feedbackPanel.Visible = true;
                lblError.Text         = "Invalide datas.";
                return;
            }

            if (drpListOfPlaces.SelectedValue == "Selecteer een plek")
            {
                feedbackPanel.Visible = true;
                lblError.Text         = "Selecteer eerst een plek om een reservering te plaatsen.";
                return;
            }

            // variables
            Count = 0;

            // Counting field of reservations
            Count = CheckEmptyEmailCount(Email1, Count);
            Count = CheckEmptyEmailCount(Email2, Count);
            Count = CheckEmptyEmailCount(Email3, Count);
            Count = CheckEmptyEmailCount(Email4, Count);
            Count = CheckEmptyEmailCount(Email5, Count);

            // Leader information
            var lFirstname = leader_first_name.Text;
            var lSurname   = leader_last_name.Text;
            var lAddress   = leader_address.Text;
            var lCity      = leader_city.Text;
            var lUsername  = leader_Username.Text;
            var lIban      = leader_iban.Text;
            var lEmail     = leader_Email.Text;
            var lPass      = leader_Password.Text;

            PlaceId = Convert.ToInt32(drpListOfPlaces.SelectedValue);
            var reservationOnPlace = LogicCollection.ReservationLogic.GetCountReservationOfPlace(PlaceId);

            if ((Count + 1 + reservationOnPlace) > LogicCollection.PlaceLogic.GetPlaceByID(PlaceId).Capacity)
            {
                feedbackPanel.Visible = true;
                lblError.Text         = "Teveel mensen willen op de plek ingeschreven worden.";
                return; // Too much people on that place
            }

            // Making person of leader
            var person = new Person(0, lFirstname, lSurname, lAddress, lCity, lIban); // local person

            if (!LogicCollection.PersonLogic.Insert(person))
            {
                return;
            }                                                    // insert person
            person = LogicCollection.PersonLogic.GetLastAdded(); // get person out of database

            // Register leader
            var lhash      = Membership.GeneratePassword(8, 2);
            var leaderUser = new User(0, lUsername, lEmail, lhash, false, lPass);

            if (!LogicCollection.UserLogic.RegisterUser(leaderUser))
            {
                return;
            }
            leaderUser = LogicCollection.UserLogic.GetLastAdded();

            // Making reservation
            var reservation = new Reservation(0, person.ID, StartDate.SelectedDate, EndDate.SelectedDate, false); // local reservation

            if (!LogicCollection.ReservationLogic.Insert(reservation))
            {
                return;
            }                                                              // insert reservation
            reservation = LogicCollection.ReservationLogic.GetLastAdded(); // get reservation out of database

            // Reservation Wristband leader
            var resvationWristband = new ReservationWristband(0, reservation.ID, leaderUser.ID);

            if (!LogicCollection.ReservationWristbandLogic.Insert(resvationWristband))
            {
                return;
            }                                                                                   // insert reservation
            resvationWristband = LogicCollection.ReservationWristbandLogic.GetLastAdded();

            // sending reservation mail to leader
            try
            {
                LogicCollection.ReservationLogic.ReservationMail(leaderUser, CurEvent,
                                                                 LogicCollection.PlaceLogic.GetPlaceByID(PlaceId), reservation.DateStart, reservation.DateEnd);
            }
            catch (Exception)
            {
                return;
            }

            // Making reservation_account
            var reservationAccount = new ReservationAccount(0, reservation.ID, PlaceId);

            if (!LogicCollection.ReservationLogic.InsertReservationAccount(reservationAccount))
            {
                return;
            }


            #region checking reservations emailadresses & Reservations of users

            // Listof Textboxes
            var listOfEmailReservation = new List <TextBox>()
            {
                Email1, Email2, Email3, Email4, Email5
            };

            var reservationsOfNewUser = new List <User>();
            // Checking Emailadres if not empty
            foreach (var email in listOfEmailReservation.Where(email => CheckEmptyEmailStatus(email)))
            {
                if (!LogicCollection.UserLogic.IsValidEmail(email.Text) || email == leader_Email)
                {
                    feedbackPanel.Visible = true;
                    lblError.Text         = "Invalide emailadressen.";
                    return;
                }

                var result = Regex.Match(email.Text, @"^.*?(?=@)").Value;

                var hash = Membership.GeneratePassword(8, 0);
                reservationsOfNewUser.Add(new User(0, result, email.Text, hash, false, null));
            }

            // Adding user to database and make reservation
            foreach (var user in reservationsOfNewUser)
            {
                // checking if users is not null send email and insert into database
                if (user == null)
                {
                    continue;
                }

                //send email and insert into database and make reservationAccount
                var password = Membership.GeneratePassword(10, 0);
                var register = LogicCollection.UserLogic.RegisterUser(user, true, password);
                var userLast = LogicCollection.UserLogic.GetLastAdded();

                if (!register)
                {
                    continue;
                }
                //var res = new ReservationAccount(0, reservation.ID, PlaceId);
                //if (!LogicCollection.ReservationLogic.InsertReservationAccount(res)) { return; }

                var resvationWristGuest = new ReservationWristband(0, reservation.ID, userLast.ID);
                if (!LogicCollection.ReservationWristbandLogic.Insert(resvationWristGuest))
                {
                    return;
                }                                                                                       // insert reservationWristband

                //sending reservation mail to newUser
                try
                {
                    LogicCollection.ReservationLogic.ReservationMail(userLast, CurEvent,
                                                                     LogicCollection.PlaceLogic.GetPlaceByID(PlaceId), reservation.DateStart, reservation.DateEnd);
                }
                catch (Exception)
                {
                    return;
                }
            }
            #endregion

            // Feedbackpanels
            feedbackPanel.Visible       = false;
            feedbackPanelSucces.Visible = true;
            fromRegister.Visible        = false;

            lblSucces.Visible = true;
            lblSucces.Text    =
                (IsValid ? "Succesvol geregisteerd! Login om je reservering te betalen." : "Invalide gegevens") +
                "<br />Voornaam: " + lFirstname +
                "<br />Achternaam: " + lSurname +
                "<br />Adres: " + lAddress +
                "<br />Woonplaats: " + lCity +
                "<br />IBAN: " + lIban +
                "<br />Email: " + lEmail +
                "<br />Meerdere reserveerders: " + Count +
                "<br />PlaceID: " + PlaceId +
                "<br />Startdatum: " + StartDate.SelectedDate.ToShortDateString() +
                "<br />Einddatum: " + EndDate.SelectedDate.ToShortDateString() +
                "<br /><a href='/Views/AccountSystem/Login.aspx'>Nu inloggen</a>";
        }
Beispiel #2
0
        /// <summary>
        /// Creates the facebook user
        /// </summary>
        /// <param name="facebookUser">
        /// The facebook user.
        /// </param>
        /// <param name="userGender">
        /// The user gender.
        /// </param>
        /// <param name="message">
        /// The message.
        /// </param>
        /// <returns>
        /// Returns if the login was successfully or not
        /// </returns>
        private bool CreateFacebookUser(FacebookUser facebookUser, int userGender, out string message)
        {
            if (YafContext.Current.Get <YafBoardSettings>().DisableRegistrations)
            {
                message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED");
                return(false);
            }

            // Check user for bot
            var    spamChecker = new YafSpamCheck();
            string result;
            var    isPossibleSpamBot = false;

            var userIpAddress = YafContext.Current.Get <HttpRequestBase>().GetUserRealIPAddress();

            // Check content for spam
            if (spamChecker.CheckUserForSpamBot(facebookUser.UserName, facebookUser.Email, userIpAddress, out result))
            {
                YafContext.Current.Get <ILogger>().Log(
                    null,
                    "Bot Detected",
                    "Bot Check detected a possible SPAM BOT: (user name : '{0}', email : '{1}', ip: '{2}', reason : {3}), user was rejected."
                    .FormatWith(facebookUser.UserName, facebookUser.Email, userIpAddress, result),
                    EventLogTypes.SpamBotDetected);

                if (YafContext.Current.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(1))
                {
                    // Flag user as spam bot
                    isPossibleSpamBot = true;
                }
                else if (YafContext.Current.Get <YafBoardSettings>().BotHandlingOnRegister.Equals(2))
                {
                    message = YafContext.Current.Get <ILocalization>().GetText("BOT_MESSAGE");

                    if (!YafContext.Current.Get <YafBoardSettings>().BanBotIpOnDetection)
                    {
                        return(false);
                    }

                    YafContext.Current.GetRepository <BannedIP>()
                    .Save(
                        null,
                        userIpAddress,
                        "A spam Bot who was trying to register was banned by IP {0}".FormatWith(userIpAddress),
                        YafContext.Current.PageUserID);

                    // Clear cache
                    YafContext.Current.Get <IDataCache>().Remove(Constants.Cache.BannedIP);

                    if (YafContext.Current.Get <YafBoardSettings>().LogBannedIP)
                    {
                        YafContext.Current.Get <ILogger>()
                        .Log(
                            null,
                            "IP BAN of Bot During Registration",
                            "A spam Bot who was trying to register was banned by IP {0}".FormatWith(
                                userIpAddress),
                            EventLogTypes.IpBanSet);
                    }

                    return(false);
                }
            }

            MembershipCreateStatus status;

            var memberShipProvider = YafContext.Current.Get <MembershipProvider>();

            var pass           = Membership.GeneratePassword(32, 16);
            var securityAnswer = Membership.GeneratePassword(64, 30);

            var user = memberShipProvider.CreateUser(
                facebookUser.UserName,
                pass,
                facebookUser.Email,
                memberShipProvider.RequiresQuestionAndAnswer ? "Answer is a generated Pass" : null,
                memberShipProvider.RequiresQuestionAndAnswer ? securityAnswer : null,
                true,
                null,
                out status);

            // setup initial roles (if any) for this user
            RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, facebookUser.UserName);

            // create the user in the YAF DB as well as sync roles...
            var userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID);

            // create empty profile just so they have one
            var userProfile = YafUserProfile.GetProfile(facebookUser.UserName);

            userProfile.Facebook   = facebookUser.ProfileURL;
            userProfile.FacebookId = facebookUser.UserID;
            userProfile.Homepage   = facebookUser.ProfileURL;

            if (facebookUser.Birthday.IsSet())
            {
                DateTime userBirthdate;
                var      ci = CultureInfo.CreateSpecificCulture("en-US");
                DateTime.TryParse(facebookUser.Birthday, ci, DateTimeStyles.None, out userBirthdate);

                if (userBirthdate > DateTimeHelper.SqlDbMinTime().Date)
                {
                    userProfile.Birthday = userBirthdate;
                }
            }

            userProfile.RealName = facebookUser.Name;
            userProfile.Gender   = userGender;

            if (facebookUser.Location != null && facebookUser.Location.Name.IsSet())
            {
                userProfile.Location = facebookUser.Location.Name;
            }

            userProfile.Save();

            // setup their initial profile information
            userProfile.Save();

            if (userID == null)
            {
                // something is seriously wrong here -- redirect to failure...
                message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED");
                return(false);
            }

            if (YafContext.Current.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet())
            {
                // send user register notification to the following admin users...
                YafContext.Current.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value);
            }

            if (isPossibleSpamBot)
            {
                YafContext.Current.Get <ISendNotification>().SendSpamBotNotificationToAdmins(user, userID.Value);
            }

            // send user register notification to the user...
            YafContext.Current.Get <ISendNotification>()
            .SendRegistrationNotificationToUser(user, pass, securityAnswer, "NOTIFICATION_ON_FACEBOOK_REGISTER");

            // save the time zone...
            var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey);

            LegacyDb.user_save(
                userId,
                YafContext.Current.PageBoardID,
                facebookUser.UserName,
                facebookUser.UserName,
                facebookUser.Email,
                0,
                null,
                null,
                true,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null);

            var autoWatchTopicsEnabled = YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting
                                         == UserNotificationSetting.TopicsIPostToOrSubscribeTo;

            // save the settings...
            LegacyDb.user_savenotification(
                userId,
                true,
                autoWatchTopicsEnabled,
                YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting,
                YafContext.Current.Get <YafBoardSettings>().DefaultSendDigestEmail);

            // save avatar
            LegacyDb.user_saveavatar(
                userId,
                "https://graph.facebook.com/{0}/picture".FormatWith(facebookUser.UserID),
                null,
                null);

            YafContext.Current.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId));

            YafSingleSignOnUser.LoginSuccess(AuthService.facebook, user.UserName, userId, true);

            message = string.Empty;

            return(true);
        }
Beispiel #3
0
        public E_RESULTADO InsertarActualizarTokenEvaluadores(int pIdPeriodo, int?pIdEvaluador, string pClUsuario, string pNbPrograma, int?pIdRol)
        {
            PeriodoOperaciones oPeriodo = new PeriodoOperaciones();

            XElement vXmlEvaluadores = new XElement("EVALUADORES");

            List <SPE_OBTIENE_FYD_EVALUADORES_TOKEN_Result> vLstEvaluadores = new List <SPE_OBTIENE_FYD_EVALUADORES_TOKEN_Result>();

            if (pIdEvaluador == null)
            {
                vLstEvaluadores = oPeriodo.ObtenerTokenEvaluadores(pIdPeriodo, pIdRol: pIdRol);
            }
            else
            {
                vLstEvaluadores.Add(new SPE_OBTIENE_FYD_EVALUADORES_TOKEN_Result()
                {
                    ID_EVALUADOR = pIdEvaluador ?? 0
                });
            }

            if (vLstEvaluadores.Count > 0)
            {
                vLstEvaluadores.ForEach(f => vXmlEvaluadores.Add(new XElement("EVALUADOR", new XAttribute("ID_EVALUADOR", f.ID_EVALUADOR), new XAttribute("CL_TOKEN", Membership.GeneratePassword(12, 1)))));
            }

            return(UtilRespuesta.EnvioRespuesta(oPeriodo.InsertarActualizarTokenEvaluadores(pIdPeriodo, vXmlEvaluadores, pClUsuario, pNbPrograma)));
        }
        public string CreateRandomPassword()
        {
            string a = Membership.GeneratePassword(6, 0);

            return(Regex.Replace(a, @"[^a-zA-Z0-9]", m => "9"));
        }
Beispiel #5
0
 /// <summary>
 /// Generate Password
 /// </summary>
 /// <param name="lenght"></param>
 /// <param name="nbrOfNonAlphabitic"></param>
 /// <returns></returns>
 public static string GeneratePassword(int lenght, int nbrOfNonAlphabitic = 0)
 {
     return(Membership.GeneratePassword(lenght, nbrOfNonAlphabitic));
 }
        private async void Install()
        {
            await Task.Run(() => {
                try
                {
                    SendProgress("DQM用バージョンを作成しています。");

                    string displayVersion = "";
                    string forgePath      = "";
                    string premisePath    = "";
                    string bodyPath       = "";
                    string libPath        = "";
                    string sePath         = "";
                    string skinPath       = "";
                    Dispatcher.Invoke(() =>
                    {
                        displayVersion = DisplayVersion.Text;
                        forgePath      = Forge.Text;
                        premisePath    = PremiseMod.Text;
                        bodyPath       = BodyMod.Text;
                        libPath        = ForgeLib.Text;
                        sePath         = Sound.Text;
                        skinPath       = Skin.Text;
                    });

                    if (!File.Exists($"{mcPath}\\versions\\1.5.2\\1.5.2.jar"))
                    {
                        ShowErrorMessage("Minecraft 1.5.2 実行ファイルが見つかりません。Minecraft 1.5.2を1回も起動していない可能性があります。もう一度動画を見てやり直してみてください。");
                        CancelInstalling();
                        return;
                    }

                    // DQM用バージョンディレクトリ作成
                    Directory.CreateDirectory($"{mcPath}\\versions\\{displayVersion}");
                    var jarPath = $"{mcPath}\\versions\\{displayVersion}\\{displayVersion}.jar";
                    SendProgress("準備中");
                    if (File.Exists(jarPath))
                    {
                        if (MessageBox.Show("指定されたバージョンはすでに存在します。上書きしますか?", "確認", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.No)
                        {
                            CancelInstalling();
                            return;
                        }
                    }
                    // JARファイルコピー
                    File.Copy($"{mcPath}\\versions\\1.5.2\\1.5.2.jar", jarPath, true);

                    SendProgress("DQM用バージョンを作成しています。");

                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                    // JSONの書き込み

                    var vJsonPath = Path.Combine(exePath, "assets", "dqm4.json");
                    if (!File.Exists(vJsonPath))
                    {
                        MessageBox.Show("dqm4.jsonが見つかりません。実行ファイルだけ別の場所に移動していませんか?", "エラー", MessageBoxButton.OK, MessageBoxImage.Error);
                        CancelInstalling();
                        return;
                    }
                    using (var vJsonReader = new StreamReader(vJsonPath))
                    {
                        var vJson   = JObject.Parse(vJsonReader.ReadToEnd());
                        vJson["id"] = displayVersion;
                        // JSONの書き込み
                        File.WriteAllText($"{mcPath}\\versions\\{displayVersion}\\{displayVersion}.json", vJson.ToString());

                        UpdateProgressBar(1);
                        using (var libArchive = ZipFile.OpenRead(libPath))
                        {
                            SendProgress("libファイルの展開中です。");
                            libArchive.ExtractToDirectory(mcPath + "\\lib", true);
                        }

                        SendProgress("プロファイルの登録中です。");
                        var launcherProfilePath = mcPath + "\\launcher_profiles.json";
                        if (!File.Exists(launcherProfilePath))
                        {
                            ShowErrorMessage("プロファイル一覧ファイルが見つかりません。ランチャーを1回も起動していない可能性があります。もう一度動画を見てやり直してみてください。");
                            CancelInstalling();
                            return;
                        }
                        var reader = new StreamReader(launcherProfilePath, Encoding.GetEncoding("UTF-8"));
                        var json   = reader.ReadToEnd();
                        reader.Close();

                        var jObject              = JObject.Parse(json);
                        var profile              = new JObject();
                        profile["created"]       = DateTime.Now.ToString();
                        profile["lastVersionId"] = displayVersion;
                        profile["name"]          = displayVersion;
                        profile["type"]          = "custom";
                        jObject["profiles"][Membership.GeneratePassword(32, 0)] = profile;

                        File.WriteAllText(launcherProfilePath, jObject.ToString());

                        SendProgress("クリーンアップ中です。");
                        if (Directory.Exists(tempPath))
                        {
                            try
                            {
                                Directory.Delete(Path.Combine(tempPath, "forge"), true);
                                Directory.Delete(Path.Combine(tempPath, "premise"), true);
                                Directory.Delete(Path.Combine(tempPath, "skin"), true);
                            } catch (Exception e) { }
                        }

                        UpdateProgressBar(2);
                        procedure = "xf";
                        SendProgress("Forgeの展開中です。");
                        var szPath = Path.Combine(exePath, "bin/7za.exe");
                        ExtractToDirectoryWithSevenZip(forgePath, $"{tempPath}\\forge");
                        UpdateProgressBar(3);
                        procedure = "aj";
                        SendProgress("JARファイルの作成中です。");
                        AddEntryToZipFileWithSevenZip(jarPath, $"{tempPath}\\forge\\*");
                        DeleteEntryFromZipFile(jarPath, "META-INF");
                        UpdateProgressBar(4);

                        ExtractPreAndBody(premisePath, jarPath, bodyPath, false);

                        using (var seArchive = ZipFile.OpenRead(sePath))
                        {
                            SendProgress("DQM SE/BGMの展開中です。");
                            seArchive.ExtractToDirectory(mcPath, true);
                        }
                        UpdateProgressBar(8);


                        if (!File.Exists(Path.Combine(tempPath, "resources.zip")))
                        {
                            SendProgress("バニラSEのダウンロード中です。");

                            var soundClient = new WebClient();
                            soundClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(MCSoundDownloadProgressChanged);
                            soundClient.DownloadFileCompleted   += new System.ComponentModel.AsyncCompletedEventHandler(OnMCSoundDownloadCompleted);

                            soundClient.DownloadFileAsync(new Uri("https://app.chikach.net/dist/resources.zip"), Path.Combine(tempPath, "resources.zip"));
                        }
                        else
                        {
                            OnMCSoundDownloadCompleted(null, null);
                        }
                    }
                }
                catch (Exception e)
                {
                    ShowErrorMessage(e.Message);
                    CancelInstalling();
                }
            });
        }
 public static string GenerateHash(string password, ref string salt)
 {
     salt = salt ?? Membership.GeneratePassword(5, 1);
     return(CalculateHash(password, salt));
 }
Beispiel #8
0
 public string GeneratePassword()
 {
     return(Membership.GeneratePassword(8, 0));
 }
Beispiel #9
0
        /// <summary>
        /// Creates the Google user
        /// </summary>
        /// <param name="googleUser">
        /// The Google user.
        /// </param>
        /// <param name="userGender">
        /// The user gender.
        /// </param>
        /// <param name="message">
        /// The message.
        /// </param>
        /// <returns>
        /// Returns if the login was successfully or not
        /// </returns>
        private static bool CreateGoogleUser(GoogleUser googleUser, int userGender, out string message)
        {
            if (BoardContext.Current.Get <BoardSettings>().DisableRegistrations)
            {
                message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED");
                return(false);
            }

            // Check user for bot
            var isPossibleSpamBot = false;

            var userIpAddress = BoardContext.Current.Get <HttpRequestBase>().GetUserRealIPAddress();

            // Check content for spam
            if (BoardContext.Current.Get <ISpamCheck>().CheckUserForSpamBot(googleUser.UserName, googleUser.Email, userIpAddress, out var result))
            {
                BoardContext.Current.Get <ILogger>().Log(
                    null,
                    "Bot Detected",
                    $"Bot Check detected a possible SPAM BOT: (user name : '{googleUser.UserName}', email : '{googleUser.Email}', ip: '{userIpAddress}', reason : {result}), user was rejected.",
                    EventLogTypes.SpamBotDetected);

                if (BoardContext.Current.Get <BoardSettings>().BotHandlingOnRegister.Equals(1))
                {
                    // Flag user as spam bot
                    isPossibleSpamBot = true;
                }
                else if (BoardContext.Current.Get <BoardSettings>().BotHandlingOnRegister.Equals(2))
                {
                    message = BoardContext.Current.Get <ILocalization>().GetText("BOT_MESSAGE");

                    if (!BoardContext.Current.Get <BoardSettings>().BanBotIpOnDetection)
                    {
                        return(false);
                    }

                    BoardContext.Current.GetRepository <BannedIP>()
                    .Save(
                        null,
                        userIpAddress,
                        $"A spam Bot who was trying to register was banned by IP {userIpAddress}",
                        BoardContext.Current.PageUserID);

                    // Clear cache
                    BoardContext.Current.Get <IDataCache>().Remove(Constants.Cache.BannedIP);

                    if (BoardContext.Current.Get <BoardSettings>().LogBannedIP)
                    {
                        BoardContext.Current.Get <ILogger>()
                        .Log(
                            null,
                            "IP BAN of Bot During Registration",
                            $"A spam Bot who was trying to register was banned by IP {userIpAddress}",
                            EventLogTypes.IpBanSet);
                    }

                    return(false);
                }
            }

            var memberShipProvider = BoardContext.Current.Get <MembershipProvider>();

            var pass           = Membership.GeneratePassword(32, 16);
            var securityAnswer = Membership.GeneratePassword(64, 30);

            var user = memberShipProvider.CreateUser(
                googleUser.UserName,
                pass,
                googleUser.Email,
                memberShipProvider.RequiresQuestionAndAnswer ? "Answer is a generated Pass" : null,
                memberShipProvider.RequiresQuestionAndAnswer ? securityAnswer : null,
                true,
                null,
                out var status);

            // setup initial roles (if any) for this user
            RoleMembershipHelper.SetupUserRoles(BoardContext.Current.PageBoardID, googleUser.UserName);

            // create the user in the YAF DB as well as sync roles...
            var userID = RoleMembershipHelper.CreateForumUser(user, BoardContext.Current.PageBoardID);

            // create empty profile just so they have one
            var userProfile = YafUserProfile.GetProfile(googleUser.UserName);

            // setup their initial profile information
            userProfile.Save();

            userProfile.GoogleId = googleUser.UserID;
            userProfile.Homepage = googleUser.ProfileURL;

            userProfile.Gender = userGender;

            if (BoardContext.Current.Get <BoardSettings>().EnableIPInfoService)
            {
                var userIpLocator = BoardContext.Current.Get <IIpInfoService>().GetUserIpLocator();

                if (userIpLocator != null)
                {
                    userProfile.Country = userIpLocator["CountryCode"];

                    var location = new StringBuilder();

                    if (userIpLocator["RegionName"] != null && userIpLocator["RegionName"].IsSet() &&
                        !userIpLocator["RegionName"].Equals("-"))
                    {
                        location.Append(userIpLocator["RegionName"]);
                    }

                    if (userIpLocator["CityName"] != null && userIpLocator["CityName"].IsSet() &&
                        !userIpLocator["CityName"].Equals("-"))
                    {
                        location.AppendFormat(", {0}", userIpLocator["CityName"]);
                    }

                    userProfile.Location = location.ToString();
                }
            }

            userProfile.Save();

            if (userID == null)
            {
                // something is seriously wrong here -- redirect to failure...
                message = BoardContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED");
                return(false);
            }

            if (BoardContext.Current.Get <BoardSettings>().NotificationOnUserRegisterEmailList.IsSet())
            {
                // send user register notification to the following admin users...
                BoardContext.Current.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value);
            }

            if (isPossibleSpamBot)
            {
                BoardContext.Current.Get <ISendNotification>().SendSpamBotNotificationToAdmins(user, userID.Value);
            }

            // send user register notification to the user...
            BoardContext.Current.Get <ISendNotification>()
            .SendRegistrationNotificationToUser(user, pass, securityAnswer, "NOTIFICATION_ON_GOOGLE_REGISTER");

            // save the time zone...
            var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey);

            var autoWatchTopicsEnabled = BoardContext.Current.Get <BoardSettings>().DefaultNotificationSetting
                                         == UserNotificationSetting.TopicsIPostToOrSubscribeTo;

            BoardContext.Current.GetRepository <User>().Save(
                userId,
                BoardContext.Current.PageBoardID,
                googleUser.UserName,
                googleUser.UserName,
                googleUser.Email,
                TimeZoneInfo.Local.Id,
                null,
                null,
                null,
                null,
                BoardContext.Current.Get <BoardSettings>().DefaultNotificationSetting,
                autoWatchTopicsEnabled,
                TimeZoneInfo.Local.SupportsDaylightSavingTime,
                null,
                null);

            // save the settings...
            BoardContext.Current.GetRepository <User>().SaveNotification(
                userId,
                true,
                autoWatchTopicsEnabled,
                BoardContext.Current.Get <BoardSettings>().DefaultNotificationSetting.ToInt(),
                BoardContext.Current.Get <BoardSettings>().DefaultSendDigestEmail);

            // save avatar
            BoardContext.Current.GetRepository <User>().SaveAvatar(userId, googleUser.ProfileImage, null, null);

            BoardContext.Current.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId));

            SingleSignOnUser.LoginSuccess(AuthService.google, user.UserName, userId, true);

            message = string.Empty;

            return(true);
        }
        public ActionResult Update(UpdateViewModel user)
        {
            ViewData["userPosition"] = getUserRoles();
            try
            {
                ApplicationDbContext _db = new ApplicationDbContext();
                var staff        = (ApplicationUser)UserManager.FindById(user.Id);
                var ExStaff      = _db.Users.FirstOrDefault(u => u.staffID == user.staffID);
                var ExStaffEmail = _db.Users.FirstOrDefault(u => u.Email == user.Email);
                if (ExStaff != null)
                {
                    if (user.Id != ExStaff.Id)
                    {
                        TempData["formStatus"]    = false;
                        TempData["formStatusMsg"] = $"<b>ALERT</b>: Staff ID/Email has been taken by another staff.";
                        return(View("Edit", user));
                    }
                }
                if (ExStaffEmail != null)
                {
                    if (user.Id != ExStaffEmail.Id)
                    {
                        TempData["formStatus"]    = false;
                        TempData["formStatusMsg"] = $"<b>ALERT</b>: Staff ID/Email has been taken by another staff.";
                        return(View("Edit", user));
                    }
                }

                UserManager.RemoveFromRole(staff.Id, UserRole.getRole(staff.position));
                UserManager.SetEmail(staff.Id, user.Email);

                staff.staffID  = user.staffID;
                staff.name     = user.name;
                staff.IC       = user.IC;
                staff.position = user.position;
                staff.status   = user.status;
                UserManager.AddToRole(staff.Id, UserRole.getRole(staff.position));

                var result = UserManager.Update(staff);

                if (!result.Succeeded)
                {
                    ViewData["userPosition"]  = getUserRoles();
                    TempData["formStatus"]    = false;
                    TempData["formStatusMsg"] = $"<b>ALERT</b>: {result.Errors}";
                    return(View("Edit", user));
                }

                TempData["formStatus"]    = true;
                TempData["formStatusMsg"] = $"<b>STATUS</b>: Staff ({staff.staffID}) details has been successfully updated!";
                LogAction.log(this._controllerName, "POST", $"Staff ({staff.staffID}) details updated", User.Identity.GetUserId());

                //rchechbox for reset password is true
                if (user.isReset)
                {
                    UserManager.RemovePassword(staff.Id);
                    string newPassword = Membership.GeneratePassword(20, 8);
                    UserManager.AddPassword(staff.Id, newPassword);
                    //string code = UserManager.GeneratePasswordResetToken(user.Id);
                    //var reetResult=UserManager.ResetPassword(user.Id, code, newPassword);
                    LogAction.log(this._controllerName, "POST", $"Manager reset account {staff.staffID} password", User.Identity.GetUserId());
                    // Sent password reset email
                    SendMail.sendMail(staff.Email,
                                      "Rubber Roller Management System Account Password Reset",
                                      "Hi! " + staff.name + "<br/>Your account password has been reset," +
                                      "<br/> Please use the temporary password below to login to your account and <b>change the password immediately</b> after login." +
                                      "<br/><br/>Your credentials are as follow:" +
                                      "<br/>staff Id: <br/>" + staff.staffID +
                                      "<br/>Password: <br/>" + newPassword);
                    LogAction.log(this._controllerName, "POST", $"Account password reset email sent to current user: {staff.staffID}", User.Identity.GetUserId());
                    //display reset password notification
                    TempData["formStatus"]    = true;
                    TempData["formStatusMsg"] = $"<b>STATUS</b>: Staff ({staff.staffID}) details has been successfully updated!</br>A new password is sent to the Email: {staff.Email}";
                    LogAction.log(this._controllerName, "POST", $"Staff ({staff.staffID}) details updated", User.Identity.GetUserId());
                }
                return(RedirectToAction("List"));
            }
            catch (Exception ex)
            {
                TempData["formStatus"]    = false;
                TempData["formStatusMsg"] = $"<b>ALERT</b>: Oops! Something went wrong. Please try again later.";
                LogAction.log(this._controllerName, "POST", "Error: " + ex.Message, User.Identity.GetUserId());
                return(Redirect(Request.UrlReferrer.ToString()));
            }
        }
        public ActionResult CreateUser(FormCollection collection)
        {
            int    role  = Convert.ToInt32(collection["role"]);
            string email = collection["Email"];
            string fname = collection["FirstName"];
            string lname = collection["LastName"];
            string pass  = collection["Password"];

            //
            string   phone    = collection["Phone"];
            DateTime birthday = Convert.ToDateTime(collection["Birthday"]);



            Yoga_User y = new Yoga_User();

            //y.Roles_Id = db.getRoleId(role);
            y.Roles_Id = role;

            y.U_Email      = email;
            y.U_First_Name = fname;
            y.U_Last_Name  = lname;

            y.U_Phone    = phone;
            y.U_Birthday = birthday;


            // will do false so that the user need to update the temporary password
            y.Active = false;

            //  Generate temporary password and send confirmation email

            String tempPassword = Membership.GeneratePassword(8, 2);

            y.U_Password = encoder.Encode(pass);

            //string token = Guid.NewGuid().ToString();
            //Util.EmailSender.sendSignUpConfirmationTempPassword(email, token, tempPassword);



            // If teacher
            if (role == 2)
            {
                // "N/A" Me
                XDocument availabilities = new XDocument
                                           (
                    new XElement("Root",
                                 new XElement("Sunday",
                                              new XElement("Start", "N/A"),
                                              new XElement("End", "N/A")),
                                 new XElement("Monday",
                                              new XElement("Start", "N/A"),
                                              new XElement("End", "N/A")),
                                 new XElement("Tuesday",
                                              new XElement("Start", "N/A"),
                                              new XElement("End", "N/A")),
                                 new XElement("Wednesday",
                                              new XElement("Start", "N/A"),
                                              new XElement("End", "N/A")),
                                 new XElement("Thursday",
                                              new XElement("Start", "N/A"),
                                              new XElement("End", "N/A")),
                                 new XElement("Friday",
                                              new XElement("Start", "N/A"),
                                              new XElement("End", "N/A")),
                                 new XElement("Saturday",
                                              new XElement("Start", "N/A"),
                                              new XElement("End", "N/A"))
                                 ));

                y.Availability = availabilities.ToString();
            }
            if (db.ValidateUserExist(email))
            {
                return(View());
            }
            db.CreateUser(y);
            return(RedirectToAction("UserList"));
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            ApplicationDbContext _db = new ApplicationDbContext();
            var dbUser = _db.Users.Where(u => u.staffID == model.staffID || u.Email == model.Email).FirstOrDefault();

            if (dbUser != null)
            {
                ViewData["userPosition"] = getUserRoles();
                TempData["formStatus"]   = false;
                if (dbUser.staffID == model.staffID)
                {
                    TempData["formStatusMsg"] = $"<b>ALERT</b>: The staff id is already exist.";
                }
                else
                {
                    TempData["formStatusMsg"] = $"<b>ALERT</b>: The email is already exist.";
                }

                return(View(model));
            }

            // Generate random password
            ModelState.Remove("Password");
            model.Password = Membership.GeneratePassword(20, 8);
            LogAction.log(this._controllerName, "POST", $"Password generated for new user. New User: {model.staffID}", User.Identity.GetUserId());

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName = model.Email,
                    Email    = model.Email,
                    staffID  = model.staffID,
                    name     = model.name,
                    IC       = model.IC,
                    position = model.position,
                    status   = AccountStatus.ACTIVE
                };

                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    LogAction.log(this._controllerName, "POST", $"User account successfully created. New User: {model.staffID}", User.Identity.GetUserId());

                    await UserManager.AddToRoleAsync(user.Id, UserRole.getRole(user.position));

                    LogAction.log(this._controllerName, "POST", $"User role added for new user: {model.staffID} - {UserRole.getRole(user.position)}", User.Identity.GetUserId());

                    // Sent account creation email
                    SendMail.sendMail(model.Email,
                                      "Rubber Roller Management System Account Creation",
                                      "Hi ! " + model.name + "<br/>An account has been created for use of the Rubber Roller Management System with a temporary password. Please login with ur staff ID and <b>change the password immediately</b> after login." +
                                      "<br/><br/>Your credentials are as follow:" +
                                      "<br/>Staff Id: <br/>" + model.staffID +
                                      "<br/>Password: <br/>" + model.Password);
                    LogAction.log(this._controllerName, "POST", $"Account creation email sent to new user: {model.staffID}", User.Identity.GetUserId());

                    TempData["formStatus"]    = true;
                    TempData["formStatusMsg"] = "<b>STATUS</b>: Staff details has been successfully added!";
                    return(Redirect(Request.UrlReferrer.ToString()));
                }
                ModelState.AddModelError("Email", result.Errors.Last());
            }

            // If we got this far, something failed, redisplay form
            ViewData["userPosition"]  = getUserRoles();
            TempData["formStatus"]    = false;
            TempData["formStatusMsg"] = "<b>ALERT</b>: Oops! Staff details has not been successfully added.";
            return(View(model));
        }
Beispiel #13
0
        /// <summary>
        /// Creates the Google user
        /// </summary>
        /// <param name="googleUser">The Google user.</param>
        /// <param name="userGender">The user gender.</param>
        /// <param name="message">The message.</param>
        /// <returns>
        /// Returns if the login was successfully or not
        /// </returns>
        private bool CreateGoogleUser(GoogleUser googleUser, int userGender, out string message)
        {
            if (YafContext.Current.Get <YafBoardSettings>().DisableRegistrations)
            {
                message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED");
                return(false);
            }

            MembershipCreateStatus status;

            var pass           = Membership.GeneratePassword(32, 16);
            var securityAnswer = Membership.GeneratePassword(64, 30);

            MembershipUser user = YafContext.Current.Get <MembershipProvider>()
                                  .CreateUser(
                googleUser.UserName,
                pass,
                googleUser.Email,
                "Answer is a generated Pass",
                securityAnswer,
                true,
                null,
                out status);

            // setup inital roles (if any) for this user
            RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, googleUser.UserName);

            // create the user in the YAF DB as well as sync roles...
            int?userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID);

            // create empty profile just so they have one
            YafUserProfile userProfile = YafUserProfile.GetProfile(googleUser.UserName);

            userProfile.Google   = googleUser.ProfileURL;
            userProfile.GoogleId = googleUser.UserID;
            userProfile.Homepage = googleUser.ProfileURL;

            userProfile.Gender = userGender;

            userProfile.Save();

            // setup their inital profile information
            userProfile.Save();

            if (userID == null)
            {
                // something is seriously wrong here -- redirect to failure...
                message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED");
                return(false);
            }

            if (YafContext.Current.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet())
            {
                // send user register notification to the following admin users...
                YafSingleSignOnUser.SendRegistrationNotificationEmail(user);
            }

            // send user register notification to the user...
            YafContext.Current.Get <ISendNotification>()
            .SendRegistrationNotificationToUser(user, pass, securityAnswer, "NOTIFICATION_ON_GOOGLE_REGISTER");    // TODO : LOCALIZE

            // save the time zone...
            int userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey);

            LegacyDb.user_save(
                userId,
                YafContext.Current.PageBoardID,
                googleUser.UserName,
                googleUser.UserName,
                googleUser.Email,
                0,
                null,
                null,
                true,
                null,
                null,
                null,
                null,
                null,
                null,
                null,
                null);

            bool autoWatchTopicsEnabled = YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting
                                          == UserNotificationSetting.TopicsIPostToOrSubscribeTo;

            // save the settings...
            LegacyDb.user_savenotification(
                userId,
                true,
                autoWatchTopicsEnabled,
                YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting,
                YafContext.Current.Get <YafBoardSettings>().DefaultSendDigestEmail);

            // save avatar
            LegacyDb.user_saveavatar(userId, googleUser.ProfileImage, null, null);

            YafContext.Current.Get <IRaiseEvent>().Raise(new NewUserRegisteredEvent(user, userId));

            YafSingleSignOnUser.LoginSuccess(AuthService.google, user.UserName, userId, true);

            message = string.Empty;

            return(true);
        }
Beispiel #14
0
        public ActionResult CreateNew(NewClientModel model)
        {
            MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, Membership.GeneratePassword(MembershipService.MinPasswordLength, MembershipService.MinRequiredNonAlphanumericCharacters), model.Email);

            if (createStatus == MembershipCreateStatus.Success)
            {
                //Если пользователь зарегистрировался, то для своего клиента он Админ
                Roles.AddUserToRole(model.UserName, RoleNames.ADMIN);
                //Создаем клиента
                MembershipUser user   = Membership.GetUser(model.UserName);
                ClientModel    client = null;
                try
                {
                    client = ClientRepo.CreateClient(model, model.OrganizationName, user, null, model.Status, model.IsDealler);
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("", ex.Message);
                }
                if (client != null)
                {
                    bool isMailError = false;
                    try
                    {
                        MailGenerator.Mailer.Send(MailGenerator.GetClientInviteMail(user, OTSession.OperationalClient.OrganizationName, Request.RequestContext));
                    }
                    catch (Exception ex)
                    {
                        isMailError = true;
                        Trace.TraceError("Ошибка отправки уведомления об отправке пользователь {0} email {1}, ошибка {2}", user.UserName, user.Email, ex);
                    }
                    return(RedirectToAction("Index", isMailError?new { User = user, Client = client }: null));
                }
                else
                {
                    return(View(model));
                }
            }
            else
            {
                ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
            }
            return(View(model));
        }
        public async Task <ActionResult> btn_login(string username, string password, string capcha, bool remember)
        {
            string strreturn  = "";
            var    value      = "false";
            var    check_role = false;

            if (Session["randomStr"] != null)
            {
                string getSession = Session["randomStr"].ToString();
                var    list_role  = Roles.GetRolesForUser(username);
                if (list_role.Length > 0)
                {
                    for (var i = 0; i < list_role.Length; i++)
                    {
                        if (list_role[i] != "" && list_role[i] != "engineer")
                        {
                            check_role = true;
                        }
                    }
                }

                if (check_role)
                {
                    if (Membership.ValidateUser(username, password) && capcha == getSession)
                    {
                        var    dnow          = DateTime.Now.AddDays(1);
                        string formsAuthSalt = Membership.GeneratePassword(20, 2);
                        // string userData = string.Join("|", GetCustomUserRoles());

                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                            1,                                                      // ticket version
                            username,                                               // authenticated username
                            DateTime.Now,                                           // issueDate
                            new DateTime(dnow.Year, dnow.Month, dnow.Day, 0, 5, 0), // expiryDate
                            true,                                                   // true to persist across browser sessions
                            formsAuthSalt,                                          // can be used to store additional user data
                            FormsAuthentication.FormsCookiePath);                   // the path for the cookie

                        // Encrypt the ticket using the machine key
                        string encryptedTicket = FormsAuthentication.Encrypt(ticket);

                        // Add the cookie to the request to save it

                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                        cookie.Expires = remember ? DateTime.Now.AddDays(30) : DateTime.Now.AddDays(1);

                        cookie.HttpOnly = true;
                        cookie.Secure   = true;

                        Response.Cookies.Add(cookie);

                        // Your redirect logic
                        // Response.Redirect(FormsAuthentication.GetRedirectUrl(username, chkremember.Checked));

                        MembershipUser user = Membership.GetUser(username);
                        user.Comment = formsAuthSalt;
                        Membership.UpdateUser(user);
                        value = "true";


                        // login child site
                        if (Roles.IsUserInRole(username, "admin") || Roles.IsUserInRole(username, "admin_installer"))
                        {
                            var std   = new StandardController();
                            var model = new
                            {
                                data = std.GetBodyLogin(username, password, remember)
                            };

                            //string apiUrl = ConfigurationManager.AppSettings["Child_URL"] + "member/login";
                            string url = ConfigurationManager.AppSettings["Child_URL"] + "member/login?token=" + std.GetBodyLogin(username, password, remember);
                            strreturn = "{ \"status\"  : \"1\" ,  \"autourl\" : \"" + url + "\"}";

                            // Response.Redirect(apiUrl);
                            //   HttpClient client = new HttpClient();
                            //client.BaseAddress = new Uri(apiUrl);
                            //client.DefaultRequestHeaders.Accept.Clear();
                            //client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                            ////var json = JsonConvert.SerializeObject(model);
                            ////var json_body = new StringContent(json, Encoding.UTF8, "application/json");
                            ////HttpResponseMessage response = await client.PostAsync(apiUrl, json_body);
                            //HttpResponseMessage response = await client.GetAsync(apiUrl);
                            //string responseContent = await response.Content.ReadAsStringAsync();
                        }
                        else
                        {
                            strreturn = "{ \"status\"  : \"3\" ,  \"autourl\" : \"" + "" + "\"}";
                        }
                    }
                }
                else
                {
                    strreturn = "{ \"status\"  : \"2\" ,  \"autourl\" : \"" + "" + "\"}";
                    //value = "engineer";
                }
            }
            else
            {
                // value = "false";
                strreturn = "{ \"status\"  : \"0\" ,  \"autourl\" : \"" + "" + "\"}";
            }

            //  return value;
            return(Content(strreturn, "application/json"));
        }
Beispiel #16
0
        public IHttpActionResult Post([FromBody] UserModel model)
        {
            if (!Msisdn.IsValid(model.MobileNumber, Country))
            {
                return(this.BadRequestEx(Error.MobileNumberInvalid));
            }

            using (var dbContext = new DataContext())
            {
                var user = new User();
                user.FirstName        = model.FirstName;
                user.LastName         = model.LastName;
                user.Email            = model.Email;
                user.MobileNumber     = model.MobileNumber;
                user.Status           = Data.Enums.Status.Active;
                user.CreatedTimestamp = DateTime.Now;
                user.IsOfficer        = model.IsOfficer ? "1" : "0";
                user.ExternalID       = model.ExternalID;

                dbContext.Users.Add(user);

                if (model.Districts != null)
                {
                    foreach (var districtModel in model.Districts)
                    {
                        var district = dbContext.Districts.Find(districtModel.ID);
                        if (district == null)
                        {
                            continue;
                        }

                        var userDistrict = new UserDistrict();
                        userDistrict.District = district;
                        userDistrict.User     = user;

                        dbContext.UserDistricts.Add(userDistrict);
                    }
                }

                var userName = Kapsch.Core.Cryptography.Random.GenerateConcatenatedString(model.FirstName.Substring(0, 1), model.LastName);
                while (true)
                {
                    if (!dbContext.Credentials.Any(f => f.UserName == userName))
                    {
                        break;
                    }

                    userName = Kapsch.Core.Cryptography.Random.GenerateConcatenatedString(model.FirstName.Substring(0, 1), model.LastName);
                }

                Random random = new Random();

                var credential = new Credential();
                credential.CreatedTimeStamp = DateTime.Now;
                credential.EntityID         = user.ID;
                credential.EntityType       = Data.Enums.EntityType.User;
                credential.ExpiryTimeStamp  = DateTime.Now.AddYears(20);
                credential.Status           = Data.Enums.Status.Active;
                credential.UserName         = userName;

                credential.Password = Membership.GeneratePassword(8, 0);
                credential.Password = Regex.Replace(credential.Password, @"[^a-zA-Z0-9]", m => random.Next(0, 9).ToString());

                dbContext.Credentials.Add(credential);

                if (model.SystemFunctions != null)
                {
                    foreach (var systemFunctionModel in model.SystemFunctions)
                    {
                        var systemFunction = dbContext.SystemFunctions.Find(systemFunctionModel.ID);
                        if (systemFunction == null)
                        {
                            continue;
                        }

                        var userSystemFunction = new CredentialSystemFunction();
                        userSystemFunction.SystemFunction = systemFunction;
                        userSystemFunction.Credential     = credential;
                        userSystemFunction.Status         = Data.Enums.Status.Active;

                        dbContext.CredentialSystemFunctions.Add(userSystemFunction);
                    }
                }

                dbContext.SaveChanges();

                var logo = string.Format("{0}/Images/IMS-logo-180x66-1color.png", UserManagementPortal);

                var personalizations = new Dictionary <string, string>();
                personalizations.Add("website", UserManagementPortal);
                personalizations.Add("logo", logo);
                personalizations.Add("fullName", string.Format("{0} {1}", user.FirstName, user.LastName));
                personalizations.Add("userName", credential.UserName);
                personalizations.Add("password", credential.Password);

                //EmailHelper.Send(
                //    HttpContext.Current.Server.MapPath("~/MailTemplates"),
                //    new[] { model.Email },
                //    "Account Created",
                //    "AccountCreated.txt",
                //    personalizations);
                var company = dbContext.Companies.FirstOrDefault(f => f.Name == "Intelligent Mobility Solutions"); // IMS
                if (company == null)
                {
                    Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Unable to get company, Intelligent Mobility Solutions, from database."));
                }
                else
                {
                    SmsHelper.Send(
                        dbContext,
                        "User Management",
                        "Create User",
                        new Router()
                    {
                        Source = "IMS", Target = new Msisdn(user.MobileNumber, Country).ToString(Msisdn.Format.International)
                    },
                        company,
                        user,
                        HttpContext.Current.Server.MapPath("~/MailTemplates"),
                        "SmsAccountCreated.txt",
                        personalizations);
                }

                model.ID               = user.ID;
                model.UserName         = credential.UserName;
                model.Status           = (Models.Enums.UserStatus)user.Status;
                model.CreatedTimestamp = user.CreatedTimestamp;

                return(Ok(model));
            }
        }
Beispiel #17
0
        /// <summary>
        /// 生成房间秘钥
        /// </summary>
        /// <returns></returns>
        public string MadeKey()
        {
            string key = Membership.GeneratePassword(10, 0);

            return(key);
        }
Beispiel #18
0
        public HttpResponseMessage Create(string email)
        {
            // Error handling : http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling
            // Web Api return HttpResponseMessage http://stackoverflow.com/questions/12264088/asp-net-web-api-return-clr-object-or-httpresponsemessage
            MembershipUser user;

            try
            {
                user = Membership.GetUser(email);
                if (user != null)
                {
                    var message   = string.Format("The username '{0}' is already in use.", email);
                    var httpError = new HttpError(message);
                    Logger.Debug(httpError.Message);
                    httpError["error_sub_code"] = 1001; //can add custom Key-Values to HttpError
                    return(Request.CreateErrorResponse(HttpStatusCode.Conflict, httpError));
                }
            }
            catch (Exception ex)
            {
                var message = string.Format("Cannot retrieve user by username '{0}'.", email);
                Logger.DebugException(message, ex);
                var httpError = new HttpError(message);
                httpError["error_sub_code"] = 1010;
                httpError["error"]          = ex.Message;
                return(Request.CreateErrorResponse(HttpStatusCode.Conflict, httpError));
            }

            string password;

            try
            {
                password = Membership.GeneratePassword(10, 3);
                user     = Membership.CreateUser(email, password, email);
            }
            catch (Exception ex)
            {
                var message = string.Format("Cannot create user '{0}'.", email);
                Logger.DebugException(message, ex);
                var httpError = new HttpError(message);
                httpError["error_sub_code"] = 1005;
                httpError["error"]          = ex.Message;
                return(Request.CreateErrorResponse(HttpStatusCode.Conflict, httpError));
            }

            try
            {
                SetRolesForUser(email, new[] { Constants.Roles.IdentityServerUsers });
            }
            catch (Exception ex)
            {
                var message = string.Format("Cannot set role for user '{0}'.", email);
                Logger.DebugException(message, ex);
                var httpError = new HttpError(message);
                httpError["error_sub_code"] = 1007;
                httpError["error"]          = ex.Message;
                return(Request.CreateErrorResponse(HttpStatusCode.Conflict, httpError));
            }

            try
            {
                SendEmailNotification(user, password);
                return(Request.CreateResponse(HttpStatusCode.OK, Map(user)));
            }
            catch (Exception ex)
            {
                var message = string.Format("Cannot send email out for '{0}'.", email);
                Logger.DebugException(message, ex);
                var httpError = new HttpError(message);
                httpError["error_sub_code"] = 1006;
                httpError["error"]          = ex.Message;
                return(Request.CreateErrorResponse(HttpStatusCode.Conflict, httpError));
            }
        }
Beispiel #19
0
        protected override void Seed(MvcForumContext context)
        {
            #region Initial Installer Code

            //var isFirstInstall = false;

            // Add the language - If it's not already there
            const string langCulture = "en-GB";
            var          language    = context.Language.FirstOrDefault(x => x.LanguageCulture == langCulture);
            if (language == null)
            {
                //isFirstInstall = true;
                var cultureInfo = LanguageUtils.GetCulture(langCulture);
                language = new Language
                {
                    Name            = cultureInfo.EnglishName,
                    LanguageCulture = cultureInfo.Name
                };
                context.Language.Add(language);

                // Save the language
                context.SaveChanges();

                // Now add the default language strings
                var file           = HostingEnvironment.MapPath(@"~/Installer/en-GB.csv");
                var commaSeparator = new[] { ',' };
                if (file != null)
                {
                    // Unpack the data
                    var allLines = new List <string>();
                    using (var streamReader = new StreamReader(file, Encoding.UTF8, true))
                    {
                        while (streamReader.Peek() >= 0)
                        {
                            allLines.Add(streamReader.ReadLine());
                        }
                    }

                    // Read the CSV file and import all the keys and values
                    var lineCounter = 0;
                    foreach (var csvline in allLines)
                    {
                        var line = csvline;
                        if (line.StartsWith("\""))
                        {
                            line = line.Replace("\"", "");
                        }

                        lineCounter++;

                        // Only split on the first comma, so the value strings can have commas in
                        var keyValuePair = line.Split(commaSeparator, 2, StringSplitOptions.None);

                        // Get the key and value
                        var key   = keyValuePair[0];
                        var value = keyValuePair[1];

                        if (string.IsNullOrWhiteSpace(key))
                        {
                            // Ignore empty keys
                            continue;
                        }

                        if (string.IsNullOrWhiteSpace(value))
                        {
                            // Ignore empty values
                            continue;
                        }

                        // Trim both the key and value
                        key   = key.Trim();
                        value = value.Trim();

                        // Create the resource key
                        var resourceKey = new LocaleResourceKey
                        {
                            Name      = key,
                            DateAdded = DateTime.UtcNow
                        };
                        context.LocaleResourceKey.Add(resourceKey);

                        // Set the value for the resource
                        var stringResource = new LocaleStringResource
                        {
                            Language          = language,
                            LocaleResourceKey = resourceKey,
                            ResourceValue     = value
                        };
                        context.LocaleStringResource.Add(stringResource);
                    }

                    // Save the language strings
                    context.SaveChanges();
                }


                var saveRoles = false;
                // Create the admin role if it doesn't exist
                var adminRole = context.MembershipRole.FirstOrDefault(x => x.RoleName == AppConstants.AdminRoleName);
                if (adminRole == null)
                {
                    adminRole = new MembershipRole {
                        RoleName = AppConstants.AdminRoleName
                    };
                    context.MembershipRole.Add(adminRole);
                    saveRoles = true;
                }

                // Create the Standard role if it doesn't exist
                var standardRole = context.MembershipRole.FirstOrDefault(x => x.RoleName == SiteConstants.Instance.StandardMembers);
                if (standardRole == null)
                {
                    standardRole = new MembershipRole {
                        RoleName = SiteConstants.Instance.StandardMembers
                    };
                    context.MembershipRole.Add(standardRole);
                    saveRoles = true;
                }

                // Create the Guest role if it doesn't exist
                var guestRole = context.MembershipRole.FirstOrDefault(x => x.RoleName == AppConstants.GuestRoleName);
                if (guestRole == null)
                {
                    guestRole = new MembershipRole {
                        RoleName = AppConstants.GuestRoleName
                    };
                    context.MembershipRole.Add(guestRole);
                    saveRoles = true;
                }

                if (saveRoles)
                {
                    context.SaveChanges();
                }

                // Create an example Category

                if (!context.Category.Any())
                {
                    // Doesn't exist so add the example category
                    const string exampleCatName = "Example Category";
                    var          exampleCat     = new Category
                    {
                        Name           = exampleCatName,
                        ModeratePosts  = false,
                        ModerateTopics = false,
                        Slug           = ServiceHelpers.CreateUrl(exampleCatName),
                        DateCreated    = DateTime.UtcNow
                    };

                    context.Category.Add(exampleCat);
                    context.SaveChanges();
                }

                // if the settings already exist then do nothing
                // If not then add default settings
                var currentSettings = context.Setting.FirstOrDefault();
                if (currentSettings == null)
                {
                    // create the settings
                    var settings = new Settings
                    {
                        ForumName                       = "MvcForum",
                        ForumUrl                        = "http://www.mydomain.com",
                        IsClosed                        = false,
                        EnableRSSFeeds                  = true,
                        DisplayEditedBy                 = true,
                        EnablePostFileAttachments       = false,
                        EnableMarkAsSolution            = true,
                        EnableSpamReporting             = true,
                        EnableMemberReporting           = true,
                        EnableEmailSubscriptions        = true,
                        ManuallyAuthoriseNewMembers     = false,
                        EmailAdminOnNewMemberSignUp     = true,
                        TopicsPerPage                   = 20,
                        PostsPerPage                    = 20,
                        EnablePrivateMessages           = true,
                        MaxPrivateMessagesPerMember     = 50,
                        PrivateMessageFloodControl      = 1,
                        EnableSignatures                = false,
                        EnablePoints                    = true,
                        PointsAllowedToVoteAmount       = 1,
                        PointsAllowedForExtendedProfile = 1,
                        PointsAddedPerPost              = 1,
                        PointsAddedForSolution          = 4,
                        PointsDeductedNagativeVote      = 2,
                        PointsAddedPostiveVote          = 2,
                        AdminEmailAddress               = "*****@*****.**",
                        NotificationReplyEmail          = "*****@*****.**",
                        SMTPEnableSSL                   = false,
                        Theme = "Metro",
                        NewMemberStartingRole           = standardRole,
                        DefaultLanguage                 = language,
                        ActivitiesPerPage               = 20,
                        EnableAkisment                  = false,
                        EnableSocialLogins              = false,
                        EnablePolls                     = true,
                        MarkAsSolutionReminderTimeFrame = 7,
                        EnableEmoticons                 = true,
                        DisableStandardRegistration     = false
                    };

                    context.Setting.Add(settings);
                    context.SaveChanges();
                }

                // Create the initial category permissions

                // Edit Posts
                if (context.Permission.FirstOrDefault(x => x.Name == SiteConstants.Instance.PermissionEditPosts) ==
                    null)
                {
                    var permission = new Permission {
                        Name = SiteConstants.Instance.PermissionEditPosts
                    };
                    context.Permission.Add(permission);

                    // NOTE: Because this is null - We assumed it's a new install so carry on checking and adding the other permissions

                    // Read Only
                    if (context.Permission.FirstOrDefault(x => x.Name == SiteConstants.Instance.PermissionReadOnly) ==
                        null)
                    {
                        var p = new Permission {
                            Name = SiteConstants.Instance.PermissionReadOnly
                        };
                        context.Permission.Add(p);
                    }

                    // Delete Posts
                    if (context.Permission.FirstOrDefault(x =>
                                                          x.Name == SiteConstants.Instance.PermissionDeletePosts) == null)
                    {
                        var p = new Permission {
                            Name = SiteConstants.Instance.PermissionDeletePosts
                        };
                        context.Permission.Add(p);
                    }

                    // Sticky Topics
                    if (context.Permission.FirstOrDefault(x =>
                                                          x.Name == SiteConstants.Instance.PermissionCreateStickyTopics) ==
                        null)
                    {
                        var p = new Permission {
                            Name = SiteConstants.Instance.PermissionCreateStickyTopics
                        };
                        context.Permission.Add(p);
                    }

                    // Lock Topics
                    if (context.Permission.FirstOrDefault(x => x.Name == SiteConstants.Instance.PermissionLockTopics) ==
                        null)
                    {
                        var p = new Permission {
                            Name = SiteConstants.Instance.PermissionLockTopics
                        };
                        context.Permission.Add(p);
                    }

                    // Vote In Polls
                    if (context.Permission.FirstOrDefault(x =>
                                                          x.Name == SiteConstants.Instance.PermissionVoteInPolls) == null)
                    {
                        var p = new Permission {
                            Name = SiteConstants.Instance.PermissionVoteInPolls
                        };
                        context.Permission.Add(p);
                    }

                    // Create Polls
                    if (context.Permission.FirstOrDefault(x =>
                                                          x.Name == SiteConstants.Instance.PermissionCreatePolls) == null)
                    {
                        var p = new Permission {
                            Name = SiteConstants.Instance.PermissionCreatePolls
                        };
                        context.Permission.Add(p);
                    }

                    // Create Topics
                    if (context.Permission.FirstOrDefault(x =>
                                                          x.Name == SiteConstants.Instance.PermissionCreateTopics) == null)
                    {
                        var p = new Permission {
                            Name = SiteConstants.Instance.PermissionCreateTopics
                        };
                        context.Permission.Add(p);
                    }

                    // Attach Files
                    if (context.Permission.FirstOrDefault(x =>
                                                          x.Name == SiteConstants.Instance.PermissionAttachFiles) == null)
                    {
                        var p = new Permission {
                            Name = SiteConstants.Instance.PermissionAttachFiles
                        };
                        context.Permission.Add(p);
                    }

                    // Deny Access
                    if (context.Permission.FirstOrDefault(x => x.Name == SiteConstants.Instance.PermissionDenyAccess) ==
                        null)
                    {
                        var p = new Permission {
                            Name = SiteConstants.Instance.PermissionDenyAccess
                        };
                        context.Permission.Add(p);
                    }

                    // === Global Permissions === //

                    // Deny Access
                    if (context.Permission.FirstOrDefault(x =>
                                                          x.Name == SiteConstants.Instance.PermissionEditMembers) == null)
                    {
                        var p = new Permission {
                            Name = SiteConstants.Instance.PermissionEditMembers, IsGlobal = true
                        };
                        context.Permission.Add(p);
                    }

                    // Insert Editor Images
                    AddPermissionInsertEditorImages(context);

                    // Insert Create Tags
                    AddPermissionCreateTags(context);

                    // Save to the database
                    context.SaveChanges();
                }

                // Create a temp password
                var tempAdminPassword = Membership.GeneratePassword(8, 0);

                // If the admin user exists then don't do anything else
                const string adminUsername = "******";
                if (context.MembershipUser.FirstOrDefault(x => x.UserName == adminUsername) == null)
                {
                    // create the admin user and put him in the admin role
                    var admin = new MembershipUser
                    {
                        Email      = "*****@*****.**",
                        UserName   = adminUsername,
                        Password   = tempAdminPassword,
                        IsApproved = true,
                        DisableEmailNotifications = false,
                        DisablePosting            = false,
                        DisablePrivateMessages    = false,
                        CreateDate              = DateTime.UtcNow,
                        LastLockoutDate         = (DateTime)SqlDateTime.MinValue,
                        LastPasswordChangedDate = (DateTime)SqlDateTime.MinValue,
                        LastLoginDate           = DateTime.UtcNow,
                        LastActivityDate        = null,
                        IsLockedOut             = false,
                        Slug = ServiceHelpers.CreateUrl(adminUsername)
                    };

                    // Hash the password
                    var salt = StringUtils.CreateSalt(AppConstants.SaltSize);
                    var hash = StringUtils.GenerateSaltedHash(admin.Password, salt);
                    admin.Password     = hash;
                    admin.PasswordSalt = salt;

                    // Put the admin in the admin role
                    admin.Roles = new List <MembershipRole> {
                        adminRole
                    };

                    context.MembershipUser.Add(admin);
                    context.SaveChanges();

                    // Now add read me
                    const string name     = "Read Me";
                    var          category = context.Category.FirstOrDefault();
                    var          topic    = new Topic
                    {
                        Category   = category,
                        CreateDate = DateTime.UtcNow,
                        User       = admin,
                        IsSticky   = true,
                        Name       = name,
                        Slug       = ServiceHelpers.CreateUrl(name)
                    };

                    context.Topic.Add(topic);
                    context.SaveChanges();

                    var readMeText = $@"<h2>Admin Login Details</h2>
<p>We have auto created an admin user for you to manage the site</p>
<p>Username: <strong>admin</strong><br />Password: <strong>{tempAdminPassword}</strong></p>
<p>Once you have logged in, you can manage the forum <a href=""/admin/"">through the admin section</a>. </p>
<p><strong><font color=""#ff0000"">Important:</font> </strong>Please update the admin password and username before putting this site live and delete this post, or you put the security of your forum at risk.</p>
<h2>Permissions</h2> 
<p>You must <a href=""/admin/permissions/"">set the permissions</a> for each Role in the admin section, as <u>by default no permissions are enabled</u>. So for example, you might want to set 'Create Topics' to be 
    allowed for the Standard Role or no one will be able to create topics.</p>
<h2>Documentation</h2>
<p>We have some documentation on Github in the WIKI</p>
<p><a href=""https://github.com/YodasMyDad/mvcforum/wiki"">https://github.com/YodasMyDad/mvcforum/wiki</a></p>
<h2>Issues & Help</h2>
<p>If you general need help then please post on the support forums, but if you find a bug then please either raise an issue on Github or even better fix the issue and create a pull request ;)</p>
<p><a href=""https://github.com/YodasMyDad/mvcforum/pulls"">https://github.com/YodasMyDad/mvcforum/pulls</a></p>
<p><a href=""https://github.com/YodasMyDad/mvcforum/issues"">https://github.com/YodasMyDad/mvcforum/issues</a></p>";

                    var post = new Post
                    {
                        DateCreated    = DateTime.UtcNow,
                        DateEdited     = DateTime.UtcNow,
                        Topic          = topic,
                        IsTopicStarter = true,
                        User           = admin,
                        PostContent    = readMeText,
                        SearchField    = name
                    };

                    topic.LastPost = post;

                    context.Post.Add(post);
                    context.SaveChanges();
                }
            }
            else
            {
                // Do upgrades
                UpgradeData(context);
            }

            #endregion
        }
Beispiel #20
0
 public static string GenerateRandomPassword(int charSize, int especialCharSize)
 {
     return(encryptMd5(Membership.GeneratePassword(charSize, especialCharSize)));
 }
Beispiel #21
0
        /// <summary>
        /// Creates the or assign twitter user.
        /// </summary>
        /// <param name="twitterUser">
        /// The twitter user.
        /// </param>
        /// <param name="oAuth">
        /// The oAUTH.
        /// </param>
        /// <param name="message">
        /// The message.
        /// </param>
        /// <returns>
        /// Returns if the login was successfully or not
        /// </returns>
        private static bool CreateTwitterUser(TwitterUser twitterUser, OAuthTwitter oAuth, out string message)
        {
            if (YafContext.Current.Get <YafBoardSettings>().DisableRegistrations)
            {
                message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_FAILED");
                return(false);
            }

            // Create User if not exists?! Doesn't work because there is no Email
            var email = "{0}@twitter.com".FormatWith(twitterUser.UserName);

            // Check user for bot

            /*var spamChecker = new YafSpamCheck();
             * string result;
             * var isPossibleSpamBot = false;
             *
             * var userIpAddress = YafContext.Current.Get<HttpRequestBase>().GetUserRealIPAddress();
             *
             * // Check content for spam
             * if (spamChecker.CheckUserForSpamBot(twitterUser.UserName, twitterUser.Email, userIpAddress, out result))
             * {
             *  YafContext.Current.Get<ILogger>().Log(
             *      null,
             *      "Bot Detected",
             *      "Bot Check detected a possible SPAM BOT: (user name : '{0}', email : '{1}', ip: '{2}', reason : {3}), user was rejected."
             *          .FormatWith(twitterUser.UserName, twitterUser.Email, userIpAddress, result),
             *      EventLogTypes.SpamBotDetected);
             *
             *  if (YafContext.Current.Get<YafBoardSettings>().BotHandlingOnRegister.Equals(1))
             *  {
             *      // Flag user as spam bot
             *      isPossibleSpamBot = true;
             *  }
             *  else if (YafContext.Current.Get<YafBoardSettings>().BotHandlingOnRegister.Equals(2))
             *  {
             *      message = YafContext.Current.Get<ILocalization>().GetText("BOT_MESSAGE");
             *
             *      if (!YafContext.Current.Get<YafBoardSettings>().BanBotIpOnDetection)
             *      {
             *          return false;
             *      }
             *
             *      YafContext.Current.GetRepository<BannedIP>()
             *          .Save(
             *              null,
             *              userIpAddress,
             *              "A spam Bot who was trying to register was banned by IP {0}".FormatWith(userIpAddress),
             *              YafContext.Current.PageUserID);
             *
             *      // Clear cache
             *      YafContext.Current.Get<IDataCache>().Remove(Constants.Cache.BannedIP);
             *
             *      if (YafContext.Current.Get<YafBoardSettings>().LogBannedIP)
             *      {
             *          YafContext.Current.Get<ILogger>()
             *              .Log(
             *                  null,
             *                  "IP BAN of Bot During Registration",
             *                  "A spam Bot who was trying to register was banned by IP {0}".FormatWith(
             *                      userIpAddress),
             *                  EventLogTypes.IpBanSet);
             *      }
             *
             *      return false;
             *  }
             * }*/

            // Create User if not exists?!
            MembershipCreateStatus status;

            var memberShipProvider = YafContext.Current.Get <MembershipProvider>();

            var pass           = Membership.GeneratePassword(32, 16);
            var securityAnswer = Membership.GeneratePassword(64, 30);

            var user = memberShipProvider.CreateUser(
                twitterUser.UserName,
                pass,
                email,
                memberShipProvider.RequiresQuestionAndAnswer ? "Answer is a generated Pass" : null,
                memberShipProvider.RequiresQuestionAndAnswer ? securityAnswer : null,
                true,
                null,
                out status);

            // setup initial roles (if any) for this user
            RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, twitterUser.UserName);

            // create the user in the YAF DB as well as sync roles...
            int?userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID);

            // create empty profile just so they have one
            YafUserProfile userProfile = YafUserProfile.GetProfile(twitterUser.UserName);

            // setup their initial profile information
            userProfile.Save();

            userProfile.TwitterId = twitterUser.UserId.ToString();
            userProfile.Twitter   = twitterUser.UserName;
            userProfile.Homepage  = twitterUser.Url.IsSet()
                                       ? twitterUser.Url
                                       : "http://twitter.com/{0}".FormatWith(twitterUser.UserName);
            userProfile.RealName  = twitterUser.Name;
            userProfile.Interests = twitterUser.Description;
            userProfile.Location  = twitterUser.Location;

            userProfile.Save();

            if (userID == null)
            {
                // something is seriously wrong here -- redirect to failure...
                message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "SSO_TWITTER_FAILED");

                return(false);
            }

            if (YafContext.Current.Get <YafBoardSettings>().NotificationOnUserRegisterEmailList.IsSet())
            {
                // send user register notification to the following admin users...
                YafContext.Current.Get <ISendNotification>().SendRegistrationNotificationEmail(user, userID.Value);
            }

            // save the time zone...
            var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey);

            // send user register notification to the following admin users...
            SendRegistrationMessageToTwitterUser(user, pass, securityAnswer, userId, oAuth);

            var autoWatchTopicsEnabled = YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting
                                         == UserNotificationSetting.TopicsIPostToOrSubscribeTo;

            LegacyDb.user_save(
                userId,
                YafContext.Current.PageBoardID,
                twitterUser.UserName,
                null,
                email,
                0,
                null,
                null,
                null,
                null,
                null,
                null,
                YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting,
                autoWatchTopicsEnabled,
                null,
                null,
                null);

            // save the settings...
            LegacyDb.user_savenotification(
                userId,
                true,
                autoWatchTopicsEnabled,
                YafContext.Current.Get <YafBoardSettings>().DefaultNotificationSetting,
                YafContext.Current.Get <YafBoardSettings>().DefaultSendDigestEmail);

            // save avatar
            if (twitterUser.ProfileImageUrl.IsSet())
            {
                LegacyDb.user_saveavatar(userId, twitterUser.ProfileImageUrl, null, null);
            }

            LoginTwitterSuccess(true, oAuth, userId, user);

            message = YafContext.Current.Get <ILocalization>().GetText("LOGIN", "UPDATE_EMAIL");

            return(true);
        }
Beispiel #22
0
        /// <summary>
        /// Import the User From the Current Table Row
        /// </summary>
        /// <param name="row">
        /// The row with the User Information.
        /// </param>
        /// <param name="importCount">
        /// The import Count.
        /// </param>
        /// <returns>
        /// Returns the Imported User Count.
        /// </returns>
        private int ImportUser(DataRow row, int importCount)
        {
            // Also Check if the Email is unique and exists
            if (this.Get <MembershipProvider>().RequiresUniqueEmail)
            {
                if (this.Get <MembershipProvider>().GetUserNameByEmail((string)row["Email"]) != null)
                {
                    return(importCount);
                }
            }

            MembershipCreateStatus status;

            var pass             = Membership.GeneratePassword(32, 16);
            var securityAnswer   = Membership.GeneratePassword(64, 30);
            var securityQuestion = "Answer is a generated Pass";

            if (row.Table.Columns.Contains("Password") && !string.IsNullOrEmpty((string)row["Password"]) &&
                row.Table.Columns.Contains("SecurityQuestion") &&
                !string.IsNullOrEmpty((string)row["SecurityQuestion"]) &&
                row.Table.Columns.Contains("SecurityAnswer") && !string.IsNullOrEmpty((string)row["SecurityAnswer"]))
            {
                pass = (string)row["Password"];

                securityAnswer   = (string)row["SecurityAnswer"];
                securityQuestion = (string)row["SecurityQuestion"];
            }

            var user = YafContext.Current.Get <MembershipProvider>().CreateUser(
                (string)row["Name"],
                pass,
                (string)row["Email"],
                this.Get <MembershipProvider>().RequiresQuestionAndAnswer ? securityQuestion : null,
                this.Get <MembershipProvider>().RequiresQuestionAndAnswer ? securityAnswer : null,
                true,
                null,
                out status);

            // setup inital roles (if any) for this user
            RoleMembershipHelper.SetupUserRoles(YafContext.Current.PageBoardID, (string)row["Name"]);

            // create the user in the YAF DB as well as sync roles...
            var userID = RoleMembershipHelper.CreateForumUser(user, YafContext.Current.PageBoardID);

            // create empty profile just so they have one
            var userProfile = YafUserProfile.GetProfile((string)row["Name"]);

            // Add Profile Fields to User List Table.
            if (row.Table.Columns.Contains("RealName") && !string.IsNullOrEmpty((string)row["RealName"]))
            {
                userProfile.RealName = (string)row["RealName"];
            }

            if (row.Table.Columns.Contains("Blog") && !string.IsNullOrEmpty((string)row["Blog"]))
            {
                userProfile.Blog = (string)row["Blog"];
            }

            if (row.Table.Columns.Contains("Gender") && !string.IsNullOrEmpty((string)row["Gender"]))
            {
                int gender;

                int.TryParse((string)row["Gender"], out gender);

                userProfile.Gender = gender;
            }

            if (row.Table.Columns.Contains("Birthday") && !string.IsNullOrEmpty((string)row["Birthday"]))
            {
                DateTime userBirthdate;

                DateTime.TryParse((string)row["Birthday"], out userBirthdate);

                if (userBirthdate > DateTimeHelper.SqlDbMinTime())
                {
                    userProfile.Birthday = userBirthdate;
                }
            }

            if (row.Table.Columns.Contains("BlogServiceUsername") &&
                !string.IsNullOrEmpty((string)row["BlogServiceUsername"]))
            {
                userProfile.BlogServiceUsername = (string)row["BlogServiceUsername"];
            }

            if (row.Table.Columns.Contains("BlogServicePassword") &&
                !string.IsNullOrEmpty((string)row["BlogServicePassword"]))
            {
                userProfile.BlogServicePassword = (string)row["BlogServicePassword"];
            }

            if (row.Table.Columns.Contains("GoogleId") && !string.IsNullOrEmpty((string)row["GoogleId"]))
            {
                userProfile.GoogleId = (string)row["GoogleId"];
            }

            if (row.Table.Columns.Contains("Location") && !string.IsNullOrEmpty((string)row["Location"]))
            {
                userProfile.Location = (string)row["Location"];
            }

            if (row.Table.Columns.Contains("Country") && !string.IsNullOrEmpty((string)row["Country"]))
            {
                userProfile.Country = (string)row["Country"];
            }

            if (row.Table.Columns.Contains("Region") && !string.IsNullOrEmpty((string)row["Region"]))
            {
                userProfile.Region = (string)row["Region"];
            }

            if (row.Table.Columns.Contains("City") && !string.IsNullOrEmpty((string)row["City"]))
            {
                userProfile.City = (string)row["City"];
            }

            if (row.Table.Columns.Contains("Interests") && !string.IsNullOrEmpty((string)row["Interests"]))
            {
                userProfile.Interests = (string)row["Interests"];
            }

            if (row.Table.Columns.Contains("Homepage") && !string.IsNullOrEmpty((string)row["Homepage"]))
            {
                userProfile.Homepage = (string)row["Homepage"];
            }

            if (row.Table.Columns.Contains("Skype") && !string.IsNullOrEmpty((string)row["Skype"]))
            {
                userProfile.Skype = (string)row["Skype"];
            }

            if (row.Table.Columns.Contains("ICQe") && !string.IsNullOrEmpty((string)row["ICQ"]))
            {
                userProfile.ICQ = (string)row["ICQ"];
            }

            if (row.Table.Columns.Contains("XMPP") && !string.IsNullOrEmpty((string)row["XMPP"]))
            {
                userProfile.XMPP = (string)row["XMPP"];
            }

            if (row.Table.Columns.Contains("Occupation") && !string.IsNullOrEmpty((string)row["Occupation"]))
            {
                userProfile.Occupation = (string)row["Occupation"];
            }

            if (row.Table.Columns.Contains("Twitter") && !string.IsNullOrEmpty((string)row["Twitter"]))
            {
                userProfile.Twitter = (string)row["Twitter"];
            }

            if (row.Table.Columns.Contains("TwitterId") && !string.IsNullOrEmpty((string)row["TwitterId"]))
            {
                userProfile.TwitterId = (string)row["TwitterId"];
            }

            if (row.Table.Columns.Contains("Facebook") && !string.IsNullOrEmpty((string)row["Facebook"]))
            {
                userProfile.Facebook = (string)row["Facebook"];
            }

            if (row.Table.Columns.Contains("FacebookId") && !string.IsNullOrEmpty((string)row["FacebookId"]))
            {
                userProfile.FacebookId = (string)row["FacebookId"];
            }

            userProfile.Save();

            if (userID == null)
            {
                // something is seriously wrong here -- redirect to failure...
                return(importCount);
            }

            // send user register notification to the new users
            this.Get <ISendNotification>().SendRegistrationNotificationToUser(
                user, pass, securityAnswer, "NOTIFICATION_ON_REGISTER");

            // save the time zone...
            var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(user.ProviderUserKey);

            var isDst = false;

            if (row.Table.Columns.Contains("IsDST") && !string.IsNullOrEmpty((string)row["IsDST"]))
            {
                bool.TryParse((string)row["IsDST"], out isDst);
            }

            var timeZone = 0;

            if (row.Table.Columns.Contains("Timezone") && !string.IsNullOrEmpty((string)row["Timezone"]))
            {
                int.TryParse((string)row["Timezone"], out timeZone);
            }

            var autoWatchTopicsEnabled = this.Get <YafBoardSettings>().DefaultNotificationSetting
                                         == UserNotificationSetting.TopicsIPostToOrSubscribeTo;

            this.GetRepository <User>().Save(
                userId,
                YafContext.Current.PageBoardID,
                row["Name"],
                row.Table.Columns.Contains("DisplayName") ? row["DisplayName"] : null,
                row["Email"],
                timeZone,
                row.Table.Columns.Contains("LanguageFile") ? row["LanguageFile"] : null,
                row.Table.Columns.Contains("Culture") ? row["Culture"] : null,
                row.Table.Columns.Contains("ThemeFile") ? row["ThemeFile"] : null,
                row.Table.Columns.Contains("TextEditor") ? row["TextEditor"] : null,
                null,
                null,
                this.Get <YafBoardSettings>().DefaultNotificationSetting,
                autoWatchTopicsEnabled,
                isDst,
                null,
                null);

            // save the settings...
            this.GetRepository <User>().SaveNotification(
                userId,
                true,
                autoWatchTopicsEnabled,
                this.Get <YafBoardSettings>().DefaultNotificationSetting,
                this.Get <YafBoardSettings>().DefaultSendDigestEmail);

            importCount++;

            return(importCount);
        }
    protected void Button1_Click(object sender, EventArgs e)
    {
        String        connString = ConfigurationManager.ConnectionStrings["school_management_systemConnectionString"].ConnectionString;
        SqlConnection conn       = new SqlConnection();

        conn.ConnectionString = connString;
        conn.Open();
        SqlCommand cmd = new SqlCommand("staff_registration", conn);

        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@last_name", SqlDbType.VarChar).Value   = TextBox3.Text;
        cmd.Parameters.Add("@first_name", SqlDbType.VarChar).Value  = TextBox1.Text;
        cmd.Parameters.Add("@middle_name", SqlDbType.VarChar).Value = TextBox2.Text;
        cmd.Parameters.Add("@dob", SqlDbType.Date).Value            = TextBox30.Text;
        cmd.Parameters.Add("@s_address", SqlDbType.VarChar).Value   = TextArea1.InnerText;
        cmd.Parameters.Add("@mobile_no", SqlDbType.BigInt).Value    = TextBox8.Text;
        cmd.Parameters.Add("@postal_code", SqlDbType.Int).Value     = TextBox7.Text;
        String tele = "";

        if (!TextBox10.Text.ToString().Equals("") && !TextBox9.Text.ToString().Equals(""))
        {
            tele = TextBox9.Text + "-" + TextBox10.Text;
        }
        cmd.Parameters.Add("@telephone_no", SqlDbType.VarChar).Value  = tele;
        cmd.Parameters.Add("@email_id", SqlDbType.VarChar).Value      = TextBox11.Text;
        cmd.Parameters.Add("@blood_group", SqlDbType.VarChar).Value   = TextBox12.Text;
        cmd.Parameters.Add("@nationality", SqlDbType.VarChar).Value   = DropDownList1.SelectedItem.Text;
        cmd.Parameters.Add("@year_of_joining", SqlDbType.Date).Value  = TextBox31.Text;
        cmd.Parameters.Add("@qualification", SqlDbType.VarChar).Value = TextArea2.InnerText;
        if (RadioButton1.Checked)
        {
            cmd.Parameters.Add("@sex", SqlDbType.VarChar).Value = "M";
        }
        else
        {
            cmd.Parameters.Add("@sex", SqlDbType.VarChar).Value = "F";
        }
        cmd.Parameters.Add("@department", SqlDbType.VarChar).Value = DropDownList2.SelectedItem.ToString();
        string password = Membership.GeneratePassword(5, 0);

        cmd.Parameters.Add("@password", SqlDbType.VarChar).Value = password;
        if (DropDownList2.SelectedItem.ToString().Equals("Management"))
        {
            cmd.Parameters.Add("@role_desc", SqlDbType.VarChar).Value = DropDownList3.SelectedItem.ToString();
        }
        else
        {
            cmd.Parameters.Add("@role_desc", SqlDbType.VarChar).Value = "Other";
        }

        if (Image1.ImageUrl.ToString().Equals(""))
        {
            cmd.Parameters.Add("@check", SqlDbType.BigInt).Value = 0;
        }
        else
        {
            cmd.Parameters.Add("@check", SqlDbType.BigInt).Value = 1;
        }
        SqlDataReader reader = cmd.ExecuteReader();

        if (reader.HasRows)
        {
            reader.Read();
            if (!Image1.ImageUrl.ToString().Equals(""))
            {
                //MessageBox.Show(HiddenField1.Value.ToString());
                System.IO.File.Move(Server.MapPath(Image1.ImageUrl.ToString()), Server.MapPath("~/Uploads/Staff/" + reader.GetValue(1).ToString()));
            }
            if (!TextBox11.Text.ToString().Equals(""))
            {
                SmtpClient smtp = new SmtpClient();
                {
                    smtp.Host           = "smtp.gmail.com";
                    smtp.Port           = 587;
                    smtp.EnableSsl      = true;
                    smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                    smtp.Credentials    = new NetworkCredential("*****@*****.**", "abhijanashakuntalam/,///");
                    smtp.Timeout        = 20000;
                }
                string message = "Your user id is:" + reader.GetValue(0).ToString() + " and password is:" + password;
                // smtp.Send("*****@*****.**",TextBox11.Text, "Registration Successful", message);
            }
            clearallcontrols(Page);
            lblMessage.Text    = "";
            HiddenField2.Value = "";
            Button2.Visible    = false;
            btnUpload.Enabled  = true;
            ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language$='text/javascript' src$='~/js/JScript'>alert('Staff Registered')</script>");
        }
        else
        {
            ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language$='text/javascript' src$='~/js/JScript'>alert('Error not updated')</script>");
            HiddenField2.Value = "";
            Button2.Visible    = false;
            btnUpload.Enabled  = true;
        }
        reader.Close();
        conn.Close();
    }
Beispiel #24
0
        public async Task <ActionResult> CreateNewUser(CreateNewUserViewModel model, List <int> AllProjects, string RoleName)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName    = model.Email,
                    Email       = model.Email,
                    FirstName   = model.FirstName,
                    LastName    = model.LastName,
                    AvatarPath  = WebConfigurationManager.AppSettings["DefaultAvatarPath"],
                    PhoneNumber = model.PhoneNumber
                };
                if (model.Avatar != null)
                {
                    if (FileUploadValidator.IsWebFriendlyImage(model.Avatar))
                    {
                        var fileName     = FileStamp.MakeUnique(model.Avatar.FileName);
                        var serverFolder = WebConfigurationManager.AppSettings["DefaultAvatarFolder"];
                        model.Avatar.SaveAs(Path.Combine(Server.MapPath(serverFolder), fileName));
                        user.AvatarPath = $"{serverFolder}{fileName}";
                    }
                }
                var result = await UserManager.CreateAsync(user, Membership.GeneratePassword(12, 1));

                if (result.Succeeded)
                {
                    roleHelper.AddUserToRole(user.Id, RoleName);

                    foreach (var projectId in AllProjects)
                    {
                        projectHelper.AddUserToProject(user.Id, projectId);
                    }


                    // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                    // Send an email with this link
                    string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);

                    try
                    {
                        var from  = "BugTracker Admin<*****@*****.**>";
                        var email = new MailMessage(from, model.Email)
                        {
                            Subject    = "Confirm Your Account",
                            Body       = "Please confirm your account by Clicking here <a href=\"" + callbackUrl + "\">here</a> ",
                            IsBodyHtml = true
                        };
                        var svc = new EmailService();
                        await svc.SendAsync(email);

                        //return View(new EmailModel());
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        await Task.FromResult(0);
                    }

                    //await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    return(RedirectToAction("Login", "Account"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            ViewBag.AllProjects = new MultiSelectList(db.Projects.ToList(), "Id", "Name");
            ViewBag.RoleName    = new SelectList(db.Roles, "Name", "Name", "Default");
            return(View(model));
        }
Beispiel #25
0
        /// <summary>
        /// Import the User From the Current Table Row
        /// </summary>
        /// <param name="row">
        /// The row with the User Information.
        /// </param>
        /// <param name="importCount">
        /// The import Count.
        /// </param>
        /// <returns>
        /// Returns the Imported User Count.
        /// </returns>
        private int ImportUser(DataRow row, int importCount)
        {
            // Also Check if the Email is unique and exists
            if (this.Get <MembershipProvider>().RequiresUniqueEmail)
            {
                if (this.Get <MembershipProvider>().GetUserNameByEmail(email: (string)row[columnName: "Email"]) != null)
                {
                    return(importCount);
                }
            }

            var pass             = Membership.GeneratePassword(length: 32, numberOfNonAlphanumericCharacters: 16);
            var securityAnswer   = Membership.GeneratePassword(length: 64, numberOfNonAlphanumericCharacters: 30);
            var securityQuestion = "Answer is a generated Pass";

            if (row.Table.Columns.Contains(name: "Password") && ((string)row[columnName : "Password"]).IsSet() &&
                row.Table.Columns.Contains(name : "SecurityQuestion") &&
                ((string)row[columnName : "SecurityQuestion"]).IsSet() &&
                row.Table.Columns.Contains(name : "SecurityAnswer") && ((string)row[columnName : "SecurityAnswer"]).IsSet())
            {
                pass = (string)row[columnName : "Password"];

                securityAnswer   = (string)row[columnName : "SecurityAnswer"];
                securityQuestion = (string)row[columnName : "SecurityQuestion"];
            }

            var user = YafContext.Current.Get <MembershipProvider>().CreateUser(
                username: (string)row[columnName: "Name"],
                password: pass,
                email: (string)row[columnName: "Email"],
                passwordQuestion: this.Get <MembershipProvider>().RequiresQuestionAndAnswer ? securityQuestion : null,
                passwordAnswer: this.Get <MembershipProvider>().RequiresQuestionAndAnswer ? securityAnswer : null,
                isApproved: true,
                providerUserKey: null,
                status: out var status);

            // setup initial roles (if any) for this user
            RoleMembershipHelper.SetupUserRoles(pageBoardID: YafContext.Current.PageBoardID, userName: (string)row[columnName: "Name"]);

            // create the user in the YAF DB as well as sync roles...
            var userID = RoleMembershipHelper.CreateForumUser(user: user, pageBoardID: YafContext.Current.PageBoardID);

            // create empty profile just so they have one
            var userProfile = YafUserProfile.GetProfile(userName: (string)row[columnName: "Name"]);

            // Add Profile Fields to User List Table.
            if (row.Table.Columns.Contains(name: "RealName") && ((string)row[columnName : "RealName"]).IsSet())
            {
                userProfile.RealName = (string)row[columnName : "RealName"];
            }

            if (row.Table.Columns.Contains(name: "Blog") && ((string)row[columnName : "Blog"]).IsSet())
            {
                userProfile.Blog = (string)row[columnName : "Blog"];
            }

            if (row.Table.Columns.Contains(name: "Gender") && ((string)row[columnName : "Gender"]).IsSet())
            {
                int.TryParse(s : (string)row[columnName : "Gender"], result : out var gender);

                userProfile.Gender = gender;
            }

            if (row.Table.Columns.Contains(name: "Birthday") && ((string)row[columnName : "Birthday"]).IsSet())
            {
                DateTime.TryParse(s : (string)row[columnName : "Birthday"], result : out var userBirthdate);

                if (userBirthdate > DateTimeHelper.SqlDbMinTime())
                {
                    userProfile.Birthday = userBirthdate;
                }
            }

            if (row.Table.Columns.Contains(name: "BlogServiceUsername") &&
                ((string)row[columnName : "BlogServiceUsername"]).IsSet())
            {
                userProfile.BlogServiceUsername = (string)row[columnName : "BlogServiceUsername"];
            }

            if (row.Table.Columns.Contains(name: "BlogServicePassword") &&
                ((string)row[columnName : "BlogServicePassword"]).IsSet())
            {
                userProfile.BlogServicePassword = (string)row[columnName : "BlogServicePassword"];
            }

            if (row.Table.Columns.Contains(name: "GoogleId") && ((string)row[columnName : "GoogleId"]).IsSet())
            {
                userProfile.GoogleId = (string)row[columnName : "GoogleId"];
            }

            if (row.Table.Columns.Contains(name: "Location") && ((string)row[columnName : "Location"]).IsSet())
            {
                userProfile.Location = (string)row[columnName : "Location"];
            }

            if (row.Table.Columns.Contains(name: "Country") && ((string)row[columnName : "Country"]).IsSet())
            {
                userProfile.Country = (string)row[columnName : "Country"];
            }

            if (row.Table.Columns.Contains(name: "Region") && ((string)row[columnName : "Region"]).IsSet())
            {
                userProfile.Region = (string)row[columnName : "Region"];
            }

            if (row.Table.Columns.Contains(name: "City") && ((string)row[columnName : "City"]).IsSet())
            {
                userProfile.City = (string)row[columnName : "City"];
            }

            if (row.Table.Columns.Contains(name: "Interests") && ((string)row[columnName : "Interests"]).IsSet())
            {
                userProfile.Interests = (string)row[columnName : "Interests"];
            }

            if (row.Table.Columns.Contains(name: "Homepage") && ((string)row[columnName : "Homepage"]).IsSet())
            {
                userProfile.Homepage = (string)row[columnName : "Homepage"];
            }

            if (row.Table.Columns.Contains(name: "Skype") && ((string)row[columnName : "Skype"]).IsSet())
            {
                userProfile.Skype = (string)row[columnName : "Skype"];
            }

            if (row.Table.Columns.Contains(name: "ICQe") && ((string)row[columnName : "ICQ"]).IsSet())
            {
                userProfile.ICQ = (string)row[columnName : "ICQ"];
            }

            if (row.Table.Columns.Contains(name: "XMPP") && ((string)row[columnName : "XMPP"]).IsSet())
            {
                userProfile.XMPP = (string)row[columnName : "XMPP"];
            }

            if (row.Table.Columns.Contains(name: "Occupation") && ((string)row[columnName : "Occupation"]).IsSet())
            {
                userProfile.Occupation = (string)row[columnName : "Occupation"];
            }

            if (row.Table.Columns.Contains(name: "Twitter") && ((string)row[columnName : "Twitter"]).IsSet())
            {
                userProfile.Twitter = (string)row[columnName : "Twitter"];
            }

            if (row.Table.Columns.Contains(name: "TwitterId") && ((string)row[columnName : "TwitterId"]).IsSet())
            {
                userProfile.TwitterId = (string)row[columnName : "TwitterId"];
            }

            if (row.Table.Columns.Contains(name: "Facebook") && ((string)row[columnName : "Facebook"]).IsSet())
            {
                userProfile.Facebook = (string)row[columnName : "Facebook"];
            }

            if (row.Table.Columns.Contains(name: "FacebookId") && ((string)row[columnName : "FacebookId"]).IsSet())
            {
                userProfile.FacebookId = (string)row[columnName : "FacebookId"];
            }

            userProfile.Save();

            if (userID == null)
            {
                // something is seriously wrong here -- redirect to failure...
                return(importCount);
            }

            // send user register notification to the new users
            this.Get <ISendNotification>().SendRegistrationNotificationToUser(
                user: user, pass: pass, securityAnswer: securityAnswer, templateName: "NOTIFICATION_ON_REGISTER");

            // save the time zone...
            var userId = UserMembershipHelper.GetUserIDFromProviderUserKey(providerUserKey: user.ProviderUserKey);

            var isDst = false;

            if (row.Table.Columns.Contains(name: "IsDST") && ((string)row[columnName : "IsDST"]).IsSet())
            {
                bool.TryParse(value : (string)row[columnName : "IsDST"], result : out isDst);
            }

            var timeZone = 0;

            if (row.Table.Columns.Contains(name: "Timezone") && ((string)row[columnName : "Timezone"]).IsSet())
            {
                int.TryParse(s : (string)row[columnName : "Timezone"], result : out timeZone);
            }

            var autoWatchTopicsEnabled = this.Get <YafBoardSettings>().DefaultNotificationSetting
                                         == UserNotificationSetting.TopicsIPostToOrSubscribeTo;

            this.GetRepository <User>().Save(
                userID: userId,
                boardID: YafContext.Current.PageBoardID,
                userName: row[columnName: "Name"],
                displayName: row.Table.Columns.Contains(name: "DisplayName") ? row[columnName: "DisplayName"] : null,
                email: row[columnName: "Email"],
                timeZone: timeZone,
                languageFile: row.Table.Columns.Contains(name: "LanguageFile") ? row[columnName: "LanguageFile"] : null,
                culture: row.Table.Columns.Contains(name: "Culture") ? row[columnName: "Culture"] : null,
                themeFile: row.Table.Columns.Contains(name: "ThemeFile") ? row[columnName: "ThemeFile"] : null,
                textEditor: row.Table.Columns.Contains(name: "TextEditor") ? row[columnName: "TextEditor"] : null,
                approved: null,
                pmNotification: null,
                autoWatchTopics: this.Get <YafBoardSettings>().DefaultNotificationSetting,
                dSTUser: autoWatchTopicsEnabled,
                hideUser: isDst,
                notificationType: null,
                null);

            // save the settings...
            this.GetRepository <User>().SaveNotification(
                userID: userId,
                pmNotification: true,
                autoWatchTopics: autoWatchTopicsEnabled,
                notificationType: this.Get <YafBoardSettings>().DefaultNotificationSetting,
                dailyDigest: this.Get <YafBoardSettings>().DefaultSendDigestEmail);

            importCount++;

            return(importCount);
        }
 public virtual string GeneratePassword()
 {
     return(Membership.GeneratePassword(MinRequiredPasswordLength, MinRequiredNonAlphanumericCharacters));
 }
        /// <summary>
        /// Создание нового аккаунта
        /// </summary>
        /// <param name="Account"></param>
        /// <param name="Message"></param>
        /// <returns></returns>
        private static bool CreateAccount(ApplicationAccount Account, out string Message)
        {
            if (Account == null)
            {
                throw new ArgumentNullException();
            }
            if (Account is ApplicationUser && (string.IsNullOrEmpty(Account.Login) || string.IsNullOrEmpty(Account.Password)))
            {
                Message = OperationResult.ArgumentsIsNull.GetDescription();
                return(false);
            }
            if (Account is SalesPoint)
            {
                if (string.IsNullOrEmpty(Account.Login))
                {
                    Regex regex        = new Regex("GS[0-9]{6}$");
                    var   login_max_id = GetAccounts().Where(x => regex.IsMatch(x.Login)).OrderByDescending(x => x.Login).ToArray()[0].Login;
                    Account.Login = $"GS{string.Format("{0:000000}", Convert.ToInt32(login_max_id.OnlyDigital()) + 1)}";
                }
                if (string.IsNullOrEmpty(Account.Password))
                {
                    Account.Password = Membership.GeneratePassword(7, 1);
                }
                Account.IdRole = (int)ApplicationAccountRoles.Diler;
            }
            try
            {
                MembershipCreateStatus status;
                var NewAccount = Membership.CreateUser(
                    Account.Login,
                    Account.Password,
                    Account.Email,
                    !string.IsNullOrEmpty(Account.PasswordQuestion) ? Account.PasswordQuestion : "Yes",
                    !string.IsNullOrEmpty(Account.PasswordAnswer) ? Account.PasswordAnswer : "No",
                    true,
                    out status);
                if (NewAccount == null || status != MembershipCreateStatus.Success)
                {
                    Message = $"{OperationResult.CreateAccountError.GetDescription()} [{status}]";
                    return(false);
                }
                //установка роли
                Roles.AddUserToRole(Account.Login, Account.Role);
                //сохранение профиля
                if (!SaveProfile((int)NewAccount.ProviderUserKey, Account.Profile, out Message))
                {
                    return(false);
                }
                //блокирование аккаунта при необходимости
                if (Account.IsLockedOut.Equals((byte)ApplicationAccountStatus.locked))
                {
                    NewAccount.LockUser();
                }

                Message = OperationResult.OK.GetDescription();
                return(true);
            }
            catch (Exception e)
            {
                GoldenSIM.Core.Logs.RegisterError(Const.DatabaseConnectionString, MethodBase.GetCurrentMethod().DeclaringType, ref e, new StackTrace(false).GetFrame(0).GetMethod().Name);
                Message = OperationResult.InternalServerError.GetDescription();
                return(false);
            }
        }
        public ActionResult Create(Student student)
        {
            if (ModelState.IsValid)
            {
                db.Students.Add(student);
                db.SaveChanges();

                string newPassword = Membership.GeneratePassword(10, 0);
                Random rnd         = new Random();
                newPassword      = Regex.Replace(newPassword, @"[^a-zA-Z0-9]", m => rnd.Next(0, 10).ToString());
                ViewBag.Password = newPassword;

                String pass = ViewBag.Password;
                WebSecurity.CreateUserAndAccount(student.EGN, ViewBag.Password);
                //WebSecurity.Login(student.EGN, ViewBag.Password);

                //var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
                //var message = new MailMessage();
                //message.To.Add(new MailAddress("*****@*****.**")); //replace with valid value
                //message.From = new MailAddress("*****@*****.**");
                //message.Subject = "Your email subject";
                //message.Body = string.Format(body, "admin",
                //                                   "*****@*****.**", newPassword);
                //message.IsBodyHtml = true;
                //var smtp = new SmtpClient();

                //var credential = new NetworkCredential
                //{
                //    UserName = "******",  // replace with valid value
                //    Password = "******"  // replace with valid value
                //};
                //smtp.Credentials = credential;
                //smtp.Host = "smtp.abv.bg";
                //smtp.Port = 587;
                //smtp.EnableSsl = true;

                ////smtp.SendMailAsync(message);
                //smtp.Send(message);
//this
                //var body = "<p>Email From: {0} ({1})</p><p>Message:</p><p>{2}</p>";
                //MailMessage mail = new MailMessage();
                //mail.To.Add(new MailAddress("*****@*****.**"));
                //mail.From = new MailAddress("*****@*****.**");
                //mail.Subject = "Your email subject";
                //mail.Body = string.Format(body, "admin",
                //                                   "*****@*****.**", newPassword); ;
                //mail.IsBodyHtml = true;
                //SmtpClient smtp = new SmtpClient("smtp.abv.bg", 587);
                //smtp.EnableSsl = true;
                //smtp.UseDefaultCredentials = false;
                //smtp.Credentials =
                //     new System.Net.NetworkCredential("*****@*****.**", "123456789");
                //smtp.Send(mail);



                //using (var smtp = new SmtpClient())
                //{
                //    await smtp.SendMailAsync(message);
                //    //return RedirectToAction("Sent");
                //}

                MembershipUser user = Membership.GetUser(student.EGN);
                //user.GetPassword();

                var roles = (SimpleRoleProvider)Roles.Provider;

                if (!roles.RoleExists("admin"))
                {
                    roles.CreateRole("admin");
                }

                if (!roles.RoleExists("student"))
                {
                    roles.CreateRole("student");
                }

                roles.AddUsersToRoles(new string[] { student.EGN }, new string[] { "student" });
            }

            return(RedirectToAction("Create", "StudentBrowse"));
            //return View(student);
        }
Beispiel #29
0
    protected void Register_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            try
            {
                // Create account and assign selected role
                string pswd = Password.Text;
                if (RndPswd.Checked)
                {
                    pswd = Membership.GeneratePassword(Membership.MinRequiredPasswordLength,
                                                       Membership.MinRequiredNonAlphanumericCharacters);
                }

                Membership.CreateUser(UserName.Text, pswd, Email.Text);
                ProfileCommon pc = new ProfileCommon();
                pc.Initialize(UserName.Text, true);
                pc.Name = StaffName.Text;
                pc.Save();
                Roles.AddUserToRole(UserName.Text, RoleList.SelectedValue);


                // Send account confirmation email
                string fileName = Server.MapPath("~/App_Data/AccountConfirmation.txt");
                string mailBody = File.ReadAllText(fileName);
                mailBody = mailBody.Replace("##Name##", StaffName.Text);
                mailBody = mailBody.Replace("##Role##", RoleList.SelectedValue);
                mailBody = mailBody.Replace("##Username##", UserName.Text);
                mailBody = mailBody.Replace("##Password##", pswd);

                MailMessage emailMessage = new MailMessage();
                emailMessage.Subject = "New Account Confirmation";
                emailMessage.Body    = mailBody;
                emailMessage.From    = new MailAddress("*****@*****.**", "NMHC");
                emailMessage.To.Add(new MailAddress(Email.Text, StaffName.Text));

                SmtpClient mySmtpClient = new SmtpClient();
                mySmtpClient.Send(emailMessage);


                // Register above staff
                using (NMHCDatabaseEntities myEntities = new NMHCDatabaseEntities())
                {
                    Hospital__Staff profile = new Hospital__Staff();
                    profile.Staff_ID  = UserName.Text;
                    profile.StaffName = StaffName.Text;
                    profile.Email     = Email.Text;
                    string h_id = (from r in myEntities.Hospital__Staff
                                   where r.Staff_ID == Profile.UserName
                                   select r.H_ID).SingleOrDefault();
                    if (h_id == null)
                    {
                        h_id = Profile.UserName;
                    }

                    profile.H_ID           = h_id;
                    profile.UpdatedBy      = Profile.UserName;
                    profile.UpdateUserName = Profile.Name;
                    profile.UpdateDateTime = DateTime.Now;

                    myEntities.AddToHospital__Staff(profile);
                    myEntities.SaveChanges();
                }

                Notification.Text = "Your account has been created successfully. " +
                                    "An email has been sent to " + Email.Text + " containing your Username and Password.";
            }
            catch (Exception ex)
            {
                Notification.Text = ex.Message;
                Back.Visible      = true;
                Continue.Visible  = false;

                // Delete partially created user data in case of exception
                using (NMHCDatabaseEntities myEntities = new NMHCDatabaseEntities())
                {
                    var profile = (from r in myEntities.Hospital__Staff
                                   where r.Staff_ID == UserName.Text
                                   select r).SingleOrDefault();
                    if (profile != null)
                    {
                        myEntities.Hospital__Staff.DeleteObject(profile);
                    }
                    myEntities.SaveChanges();
                }

                if (Membership.GetUser(UserName.Text) != null)
                {
                    Membership.DeleteUser(UserName.Text, true);
                }
            }

            MultiView1.ActiveViewIndex = 1;
        }
    }
Beispiel #30
0
        public async Task <ActionResult> RegisterEmployer(AdminRegisterEmployerViewModel model)
        {
            var password = Membership.GeneratePassword(12, 4);

            if (ModelState.IsValid)
            {
                var employer     = MapRegisterViewModelToEmployer(model);
                var identityUser = new IdentityUser
                {
                    UserName = model.LoginName,
                    Email    = model.EmailAdress
                };

                var usr = await userManager.FindByEmailAsync(model.EmailAdress);

                if (usr != null)
                {
                    ModelState.AddModelError("", EMAILADDRESS_IS_IN_USE_ERROR);
                    return(View(model));
                }

                usr = await userManager.FindByNameAsync(model.LoginName);

                if (usr != null)
                {
                    ModelState.AddModelError("", USERNAME_IS_IN_USE_ERROR);
                    return(View(model));
                }


                var result = await userManager.CreateAsync(identityUser, password);

                if (result.Succeeded)
                {
                    await userManager.AddToRoleAsync(identityUser.Id, "Employer");

                    employer.EmployerId = identityUser.Id;
                    await employerManager.Create(employer);

                    var user = await adminManager.GetBaseUserByName(User.Identity.Name);

                    var alert = new Alert();
                    {
                        alert.AlertId        = Guid.NewGuid();
                        alert.EmployerId     = employer.EmployerId;
                        alert.AlertType      = AlertType.Employer_Create;
                        alert.AlertIsDeleted = false;
                        alert.AlertCreateTS  = DateTime.Now;
                        alert.AlertUpdateTS  = DateTime.Now;
                        alert.UserId         = user.UserId;
                    };
                    await alertManager.CreateAsync(alert);

                    var messageInfo   = new AdminRegEmployerMessageBuilder(model.LoginName, password);
                    var mailingResult =
                        await mailingService.SendMailAsync(messageInfo.Body, messageInfo.Subject, model.EmailAdress);

                    return(RedirectToAction("Index", "Admin"));
                }
            }
            return(View(model));
        }