示例#1
0
        public async Task <bool> UserStartResetPassword(int userId)
        {
            Logging.Log.LogInfo($"UserStartResetPassword {userId}");
            using (var db = new Db())
            {
                var data = await db.TblUsers.FirstOrDefaultAsync(u => u.Id == userId);

                if (data == null)
                {
                    return(false);
                }

                var newPwd = PasswordHelper.GeneratePassword(5);
                data.Password     = PasswordHelper.CumputeHash(newPwd);
                data.RestPasswort = PasswordHelper.GeneratePassword();

                try
                {
                    await db.SaveChangesAsync();
                }
                catch (Exception e)
                {
                    Logging.Log.LogError($"UserResetPassword: {e}");
                    return(false);
                }

                Logging.Log.LogInfo("Send UserResetPassword");

                //SMS senden
                return(await SendPassword(data, newPwd));
            }
        }
示例#2
0
        /// <summary>
        ///     Anmelden
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="isPersistent"></param>
        /// <returns></returns>
        public async Task <bool> SignInUser(HttpContext httpContext, string username, string password, bool isPersistent = false)
        {
            try
            {
                RestAccess ra   = new RestAccess(Constants.ServiceClientEndPointWithApiPrefix);
                var        user = await ra.UserCheck(username);

                if (user.Ok && user.Result != null && !user.Result.UserIsLocked && user.Result.UserId > 0)
                {
                    var hash            = PasswordHelper.CumputeHash(password);
                    var userAccountData = await ra.UserAccountData(new ExPostUserPasswortData { UserId = user.Result.UserId, PasswordHash = hash });

                    if (userAccountData.Ok && userAccountData.Result != null && userAccountData.Result.UserAccountData != null)
                    {
                        ClaimsIdentity  identity  = new ClaimsIdentity(GetUserClaims(userAccountData.Result.UserAccountData), CookieAuthenticationDefaults.AuthenticationScheme);
                        ClaimsPrincipal principal = new ClaimsPrincipal(identity);

                        await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

                        return(true);
                    }
                }
            }
            catch (Exception)
            {
                return(false);
            }

            return(false);
        }
示例#3
0
        /// <summary>
        ///     Datenbank wird bei Aufruf erzugt bzw. gelöscht und neu erzeugt
        /// </summary>
        /// <param name="recreate">Löschen und neu erzeugen</param>
        /// <returns></returns>
        public static bool CreateAnFillUp(bool recreate = false)
        {
            return(true);

            using (var db = new Db())
            {
                if (recreate)
                {
                    db.Database.EnsureDeleted();
                }

                if (db.Database.EnsureCreated())
                {
                    var admin = new TableUser
                    {
                        PhoneNumber         = "*****@*****.**",
                        Firstname           = "Biss",
                        Lastname            = "Admin",
                        Locked              = false,
                        Password            = PasswordHelper.CumputeHash("biss"),
                        DefaultUserLanguage = "de",
                        PhoneChecked        = true,
                        IsAdmin             = true
                    };
                    db.TblUsers.Add(admin);

                    if (Constants.HasDemoUser)
                    {
                        var demo = new TableUser
                        {
                            PhoneNumber         = "*****@*****.**",
                            Firstname           = "Demo",
                            Lastname            = "User",
                            Locked              = false,
                            Password            = "",
                            DefaultUserLanguage = "de",
                            PhoneChecked        = true,
                            IsDemoUser          = true
                        };
                        db.TblUsers.Add(demo);
                    }

                    try
                    {
                        db.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        Logging.Log.LogWarning($"Datenbank Initialwerte konnten nicht erzeugt werden: {e}");
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }

                return(true);
            }
        }
示例#4
0
        /// <summary>
        ///     Anmelden
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="isPersistent"></param>
        /// <returns></returns>
        public async Task <int> SignInShop(HttpContext httpContext, string username, string password, bool isPersistent = false)
        {
            try
            {
                using (var db = new Db())
                {
                    var email = username.ToLower();

                    string pwd = PasswordHelper.CumputeHash(password.Trim());

                    var data = await db.TblStores.FirstOrDefaultAsync(u => u.EMail == email && u.Password == pwd); //TODO: Passwort check

                    if (data == null)
                    {
                        return(1);
                    }

                    if (data.Activated == false)
                    {
                        return(2);
                    }

                    var lstClaims = new List <Claim>();

                    var claims = new List <Claim>
                    {
                        new Claim(ClaimTypes.NameIdentifier, data.Id.ToString()),
                        new Claim(ClaimTypes.Name, data.CompanyName ?? ""),
                        new Claim(ClaimTypes.Email, data.EMail),
                        new Claim(ClaimTypes.Role, "Shop")
                    };


                    ClaimsIdentity  identity  = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                    ClaimsPrincipal principal = new ClaimsPrincipal(identity);

                    await httpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

                    return(0);
                }
            }
            catch (Exception)
            {
                return(1);
            }
        }
示例#5
0
        public async Task <ExCheckUser> UserCheck(string userPhone)
        {
            Logging.Log.LogInfo($"UserCheck {userPhone}");
            using (var db = new Db())
            {
                if (!PhoneHelper.IsNumber(userPhone))
                {
                    return(new ExCheckUser
                    {
                        WrongNumberFormat = true,
                    });
                }

                var numberOk = PhoneHelper.ProoveValidPhoneNumber(userPhone, out var num);

                if (!numberOk)
                {
                    return(new ExCheckUser
                    {
                        WrongNumberFormat = true,
                    });
                }

                var data = await db.TblUsers.FirstOrDefaultAsync(u => u.PhoneNumber == num);

                if (data == null)
                {
                    var newPwd      = PasswordHelper.GeneratePassword(5);
                    var newPassword = PasswordHelper.CumputeHash(newPwd);

                    data = new TableUser
                    {
                        PhoneNumber         = num,
                        Locked              = false,
                        Password            = newPassword,
                        DefaultUserLanguage = "de",
                        PhoneChecked        = true,
                    };

                    db.TblUsers.Add(data);

                    try
                    {
                        db.SaveChanges();
                    }
                    catch (Exception e)
                    {
                        Logging.Log.LogWarning($"Datenbank Initialwerte konnten nicht erzeugt werden: {e}");
                        return(new ExCheckUser
                        {
                            UserId = -1,
                            ErrorFromDb = true,
                        });
                    }

                    //SMS senden
                    try
                    {
                        await SendPassword(data, newPwd);

                        return(new ExCheckUser
                        {
                            IsNewUser = true,
                            UserId = data.Id,
                        });
                    }
                    catch (Exception e)
                    {
                        Logging.Log.LogError($"{e}");
                        return(new ExCheckUser
                        {
                            ErrorFromDb = true,
                            WrongNumberFormat = true,
                            IsNewUser = true,
                            UserId = data.Id,
                        });
                    }
                }

                if (data.IsDemoUser)
                {
                    return new ExCheckUser
                           {
                               UserIsLocked = true,
                               IsDemoUser   = true
                           }
                }
                ;

                return(new ExCheckUser
                {
                    UserIsLocked = data.Locked,
                    UserId = data.Id,
                    EMailNotChecked = !data.PhoneChecked
                });
            }
        }
        public async Task <IActionResult> StoreData([Bind("Id,CompanyName,Description,EMail,Website,Activated,CreatedAt,PostCode,City,Address,Country,FederalState,Telephonenumber,Password")]
                                                    TableStore tableStore, IFormFile logoFile)
        {
            var storeId = User.FindFirst(ClaimTypes.NameIdentifier).Value;

            if (ModelState.IsValid)
            {
                //update
                try
                {
                    var tbStore = await _context.TblStores.FirstOrDefaultAsync(x => x.Id == tableStore.Id);


                    var logo = CreateImage(logoFile, EnumImageType.Logo);
                    if (!(logo is null))
                    {
                        var storeImages = _context.TblStores.Where(s => s.Id.ToString() == storeId).Select(s => s.Images).ToArray();
                        logo.Store = tbStore;
                        if (storeImages[0].Any())
                        {
                            for (int i = 0; i < storeImages[0].Count(); i++)
                            {
                                if (storeImages[0][i].ImageType == EnumImageType.Logo)
                                {
                                    _context.TblImages.Remove(storeImages[0][i]);
                                    break;
                                }
                            }
                        }

                        _context.TblImages.Add(logo);
                    }

                    if (tbStore == null)
                    {
                        return(NotFound());
                    }

                    if (!String.IsNullOrEmpty(tableStore.Telephonenumber))
                    {
                        string outPhoneNumber;
                        var    a = ValidationHelper.ProoveValidPhoneNumber(tableStore.Telephonenumber, out outPhoneNumber);
                        //TODO: Meldung wenn nicht passt
                        tableStore.Telephonenumber = outPhoneNumber;
                    }

                    if (!String.IsNullOrEmpty(tableStore.Website))
                    {
                        if (!tableStore.Website.StartsWith("http"))
                        {
                            tableStore.Website = $"http://{tableStore.Website}";
                        }
                    }

                    tbStore.CompanyName     = tableStore.CompanyName;
                    tbStore.Description     = tableStore.Description;
                    tbStore.EMail           = tableStore.EMail;
                    tbStore.Country         = tableStore.Country;
                    tbStore.FederalState    = tableStore.FederalState;
                    tbStore.PostCode        = tableStore.PostCode;
                    tbStore.City            = tableStore.City;
                    tbStore.Address         = tableStore.Address;
                    tbStore.Website         = tableStore.Website;
                    tbStore.Telephonenumber = tableStore.Telephonenumber;

                    var sec = await _context.TblLocations.FirstOrDefaultAsync(a => a.StoreId == tbStore.Id);

                    if (sec == null)
                    {
                        sec         = new TableLocation();
                        sec.StoreId = tbStore.Id;
                        _context.TblLocations.Add(sec);
                    }

                    sec.EMail           = tbStore.EMail;
                    sec.Address         = tbStore.Address;
                    sec.City            = tbStore.City;
                    sec.Country         = tbStore.Country;
                    sec.PostCode        = tbStore.PostCode;
                    sec.Name            = tbStore.CompanyName;
                    sec.Telephonenumber = tbStore.Telephonenumber;

                    try
                    {
                        var res = GeocodeService.ConvertToGPSCoordinates(tableStore.PostCode, tableStore.City, tableStore.Address);
                        tbStore.Longitude = res.Geometry.Location.Longitude;
                        tbStore.Latitude  = res.Geometry.Location.Latitude;
                    }
                    catch (Exception e)
                    {
                    }

                    sec.Latitude  = tbStore.Latitude;
                    sec.Longitude = tbStore.Longitude;

                    if (!string.IsNullOrWhiteSpace(tableStore.Password))
                    {
                        tbStore.Password = PasswordHelper.CumputeHash(tableStore.Password);
                    }

                    await _context.SaveChangesAsync();

                    TempData.Add("message", "Daten erfolgreich gespeichert");
                    return(RedirectToAction(nameof(StoreData)));
                }
                catch (DbUpdateConcurrencyException)
                {
                    ViewData.Add("message", "Daten konnten nicht gespeichert werden");
                    return(View(tableStore));
                    //if (!TableStoreExists(store.Id))
                    //{
                    //    return NotFound();
                    //}
                    //else
                    //{
                    //    throw;
                    //}
                }
            }

            return(View(tableStore));
        }
        public async Task <ExSaveDataResult> ForgotPasswordShop(ExShopForgotPassword exShopRegistration)
        {
            using (Db db = new Db())
            {
                var shop = await db.TblStores.FirstOrDefaultAsync(a => a.EMail.ToLower() == exShopRegistration.EMail.ToLower());

                if (shop == null)
                {
                    return(new ExSaveDataResult {
                        Result = EnumSaveDataResult.Error
                    });
                }

                if (exShopRegistration.Step == EnumShopForgotPassword.Step1)
                {
                    //LINK VERSENDEN zum Ändern des Passwortes

                    BissEMail bm = new BissEMail(WebAppSettings.EmailCredentials);

                    ExEmailResetPassword er = new ExEmailResetPassword();

                    er.Message     = "Bitte bestätige den folgenden Link, damit dir ein neues Passwort zugesendet wird.";
                    er.ApproveLink = $"{Constants.WebAppBaseUrl}ShopForgotPassword/?guid={shop.ActivationCode}";

                    string email = _mailgenerator.GetPasswordResetEmail(er);

                    List <string> eMails2Inform;
                    if (Constants.CurrentAppSettings.AppConfigurationConstants == 0) //master
                    {
                        eMails2Inform = new List <string>
                        {
                            exShopRegistration.EMail
                        };                 //ToDo: Wenn die Settings Tabelle existiert dann über die Settings Tabelle
                    }
                    else
                    {
                        eMails2Inform = new List <string>
                        {
                            "*****@*****.**",
                            exShopRegistration.EMail
                        };                 //ToDo: Wenn die Settings Tabelle existiert dann über die Settings Tabelle
                    }

                    var res = await bm.SendHtmlEMail(Constants.SendEMailAs, eMails2Inform, "Passwort vergessen?", email, Constants.SendEMailAsDisplayName);
                }
                else if (exShopRegistration.Step == EnumShopForgotPassword.Step2)
                {
                    //PASSWORT VERSENDEN

                    string pwd = PasswordHelper.GeneratePassword(6);

                    shop.Password       = PasswordHelper.CumputeHash(pwd);
                    shop.ActivationCode = PasswordHelper.GeneratePassword(10);
                    await db.SaveChangesAsync();

                    BissEMail bm = new BissEMail(WebAppSettings.EmailCredentials);

                    ExEmailNewPassword er = new ExEmailNewPassword();

                    er.Message     = "Du kannst dich jetzt mit dem folgenden Passwort einloggen: ";
                    er.NewPassword = pwd;
                    er.ApproveLink = $"{Constants.WebAppBaseUrl}Activate/?guid={shop.ActivationCode}";

                    List <string> eMails2Inform;
                    if (Constants.CurrentAppSettings.AppConfigurationConstants == 0) //master
                    {
                        eMails2Inform = new List <string>
                        {
                            exShopRegistration.EMail
                        };
                    }
                    else
                    {
                        eMails2Inform = new List <string>
                        {
                            "*****@*****.**",
                            exShopRegistration.EMail
                        };                 //ToDo: Wenn die Settings Tabelle existiert dann über die Settings Tabelle
                    }

                    string email = _mailgenerator.GetNewPasswordEmail(er);

                    var res = await bm.SendHtmlEMail(Constants.SendEMailAs, eMails2Inform, "Passwort wurde geändert", email, Constants.SendEMailAsDisplayName);
                }

                return(new ExSaveDataResult());
            }
        }
        public async Task <ExSaveDataResult> RegisterShop(ExShopRegistration exShopRegistration)
        {
            using (Db db = new Db())
            {
                var shop = await db.TblStores.FirstOrDefaultAsync(a => a.EMail.ToLower() == exShopRegistration.EMail.ToLower());

                if (shop == null)
                {
                    //NEU ANLEGEN

                    shop             = new TableStore();
                    shop.EMail       = exShopRegistration.EMail.ToLower();
                    shop.CreatedAt   = DateTime.UtcNow;
                    shop.CompanyName = "";
                    db.TblStores.Add(shop);
                }
                else if (shop.Activated)
                {
                    return(new ExSaveDataResult {
                        Result = EnumSaveDataResult.Error
                    });
                }


                string pwd = PasswordHelper.GeneratePassword(6);

                shop.Password       = PasswordHelper.CumputeHash(pwd);
                shop.ActivationCode = PasswordHelper.GeneratePassword(10);
                await db.SaveChangesAsync();

                BissEMail bm = new BissEMail(WebAppSettings.EmailCredentials);

                ExEmailRegistration er = new ExEmailRegistration();

                er.Message     = $"Bitte bestätige den folgenden Link um dein Geschäft freizuschalten. Du kannst dich anschließend mit dem Passwort {pwd} einloggen";
                er.ApproveLink = $"{Constants.WebAppBaseUrl}Activate/?guid={shop.ActivationCode}";

                List <string> eMails2Inform;
                if (Constants.CurrentAppSettings.AppConfigurationConstants == 0) //master
                {
                    eMails2Inform = new List <string>
                    {
                        exShopRegistration.EMail
                    };                 //ToDo: Wenn die Settings Tabelle existiert dann über die Settings Tabelle
                }
                else
                {
                    eMails2Inform = new List <string>
                    {
                        "*****@*****.**",
                        exShopRegistration.EMail
                    };                 //ToDo: Wenn die Settings Tabelle existiert dann über die Settings Tabelle
                }

                string email = _mailgenerator.GetRegistrationEmail(er);


                var res = await bm.SendHtmlEMail(Constants.SendEMailAs, eMails2Inform, "Danke für die Registrierung", email, Constants.SendEMailAsDisplayName);

                return(new ExSaveDataResult());
            }
        }