public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
        {
            if (incomingPrincipal != null && incomingPrincipal.Identity.IsAuthenticated)
            {
                // Get the claims required to make further Graph API enquiries about the user
                //Claim nameIdClaim = incomingPrincipal.FindFirst(NameIdClaim);
                //if (nameIdClaim == null)
                //{
                //    throw new NotSupportedException("Name claim not available, role authentication is not supported");
                //}
                Claim nameClaim = incomingPrincipal.FindFirst(NameClaim);
                if (nameClaim == null)
                {
                    throw new NotSupportedException("Name claim not available, role authentication is not supported");
                }

                string userName = nameClaim.Value;
                //string currentUserObjectId = objectIdentifierClaim.Value;

                //load up the roles as RoleClaims
                TableUser user = new TableUser(userName);
                Task<IList<string>> t = _userStore.GetRolesAsync(user);
                t.RunSynchronously();
                IList<string> currentRoles = t.Result;
                foreach (string role in currentRoles)
                {
                    ((ClaimsIdentity)incomingPrincipal.Identity).AddClaim(new Claim(ClaimTypes.Role, role, ClaimValueTypes.String, _issuer));
                }
            }
            return base.Authenticate(resourceName, incomingPrincipal);
        }
Esempio n. 2
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);
            }
        }
        public static Pythonet_2prod GetInstanceForUser(int userId, int nbDiners)
        {
            try
            {
                RemoveOldUserWrapperInstances();
                if (instancePerUser.ContainsKey(userId))
                {
                    return(instancePerUser[userId].Item2);
                }

                if (nbDiners <= 0)
                {
                    // Search for NbDiners...
                    //
                    using (ShopDBModel context = new ShopDBModel())
                    {
                        TableUser tu = context.TableUsers
                                       .OrderByDescending(t => t.AssociationTimestamp)
                                       .FirstOrDefault(t => t.PersonID == userId);
                        if (tu != null)
                        {
                            int deviceId = tu.DeviceID;

                            // Firstly on the OrderHeader...
                            OrderHeader orderHeader = context.OrderHeaders.Where(oh => oh.DeviceID == deviceId).OrderByDescending(oh => oh.ID).FirstOrDefault();
                            if (orderHeader != null)
                            {
                                nbDiners = orderHeader.NbDiners;
                            }
                            else
                            {
                                // And secondly, if not found, on the Device itself.
                                int?nullableNbDiners = context.SmartTables.Where(d => d.ID == deviceId).Select(d => d.NbDiners).FirstOrDefault();
                                if (nullableNbDiners.HasValue)
                                {
                                    nbDiners = nullableNbDiners.Value;
                                }
                            }
                        }

                        if (nbDiners == 0)
                        {
                            logger.Error(nameof(GetInstanceForUser), $"Unable to get instance for user with id {userId} because nbDiners <= 0");
                            return(null);
                        }
                    }
                }

                // Create an instance for this unknown user:
                Pythonet_2prod pythonWrapper = new Pythonet_2prod();
                pythonWrapper.InitUser(userId, DateTime.Now, nbDiners);
                instancePerUser.Add(userId, new Tuple <DateTime, Pythonet_2prod>(DateTime.Now, pythonWrapper));
                return(pythonWrapper);
            }
            catch (Exception ex)
            {
                logger.Error(nameof(GetInstanceForUser), "Unable to get instance for user with id " + userId, ex);
                return(null);
            }
        }
Esempio n. 4
0
        public APIClient.TableUser GetSingleOrderData(string linkToOrder)
        {
            var tableUser = new TableUser();
            var model     = new DataModel();

            _driver.Navigate().GoToUrl(linkToOrder);
            if (IsOlxOrder(linkToOrder))
            {
            }
            else
            {
                tableUser.TableAd          = new TableAd();;
                tableUser.PhoneNumber      = GetPhoneNumberOtomoto();
                tableUser.TableAd.Location = GetLocationOtomoto();
                GetCarParameters();
                tableUser.TableAd.Model = GetModelOtomoto();
                tableUser.TableAd.Brand = GetBrandOtomoto();
                tableUser.TableAd.Fuel  = GetFuelTypeOtomoto();
                //tableUser.TableAd.HorsePower = GetHorsePowerOtomoto();
                // tableUser.Price = GetPriceOtomoto();
                //tableUser.TableAd.ProductionYear = GetYearOtomoto();
            }

            return(tableUser);
        }
Esempio n. 5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string id = Convert.ToString(Session["id"]);

            //String message = null;
            if (Session["id"] == null)
            {
                Response.Redirect("Login.aspx");
            }
            else
            {
                try
                {
                    Koneksi loadData = new Koneksi();
                    TableUser.DataSource = loadData.daftar_barang();
                    TableUser.DataBind();
                    loadData.kon.Close();
                    Riwayat.DataSource = loadData.riwayat_barang();
                    Riwayat.DataBind();
                    loadData.kon.Close();
                }catch (Exception msg)
                {
                    this.message = "terjadi masalah";
                }
            }
        }
Esempio n. 6
0
        public async Task <IActionResult> Edit(int id, [Bind("Id,Locked,PhoneNumber,PhoneChecked,DefaultUserLanguage,Password,RestPasswort,CreatedAtUtc,IsDemoUser,IsAdmin,Firstname,Lastname,Street,PostalCode,City")]
                                               TableUser tableUser)
        {
            if (id != tableUser.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(tableUser);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TableUserExists(tableUser.Id))
                    {
                        return(NotFound());
                    }

                    throw;
                }

                return(RedirectToAction(nameof(Index)));
            }

            return(View(tableUser));
        }
Esempio n. 7
0
        public async Task <IActionResult> PutTableUser([FromRoute] int id, [FromBody] TableUser tableUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (id != tableUser.id)
            {
                return(BadRequest());
            }

            _context.Entry(tableUser).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TableUserExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Esempio n. 8
0
 public void ShowExclamationPoint(TableUser UserHelping)
 {
     NotificationAvatar.ShowExclamationPoint = UserHelping == null;
     if (UserHelping != null)
     {
         NotificationAvatar.ShowCircle = true;
     }
 }
Esempio n. 9
0
        public List <TableUser> WhoEndChallange()
        {
            using (IDbConnection dbDapper = new SqlConnection(connectionString))
            {
                TableUser model = new TableUser();

                var query = "SELECT DISTINCT u.Email, u.FirstName, u.LastName FROM Challenge c INNER JOIN AspNetUsers u ON c.UserEmail = u.Email WHERE c.DaysComplete = 71";
                return(dbDapper.Query <TableUser>(query).ToList());
            }
        }
Esempio n. 10
0
        public async Task <string> PostUser()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                return("Invalid Form Input");
            }
            Dictionary <string, string> formList = new Dictionary <string, string>();
            string    root     = HttpContext.Current.Server.MapPath("~/Uploads");
            var       provider = new MultipartFormDataStreamProvider(root);
            TableUser userObj  = new TableUser();

            try
            {
                await Request.Content.ReadAsMultipartAsync(provider);

                foreach (MultipartFileData file in provider.FileData)
                {
                    filename = file.Headers.ContentDisposition.FileName;
                    if (filename.StartsWith("\"") && filename.EndsWith("\""))
                    {
                        filename = filename.Trim('"');
                    }
                    if (filename.Contains(@"/") || filename.Contains(@"\"))
                    {
                        filename = Path.GetFileName(filename);
                    }
                    filename = Guid.NewGuid() + filename;
                    File.Move(file.LocalFileName, Path.Combine(root, filename));
                }
                foreach (var key in provider.FormData.AllKeys)
                {
                    foreach (var val in provider.FormData.GetValues(key))
                    {
                        formList.Add(key, val);
                    }
                }
                userObj.FullName   = formList["FullName"];
                userObj.Username   = formList["Username"];
                userObj.Email      = formList["Email"];
                userObj.Password   = Crypto.Hash(formList["Password"]);
                userObj.Address    = formList["Address"];
                userObj.Mobile     = formList["Mobile"];
                userObj.isActive   = true;
                userObj.DisplayPic = filename;
                db.TableUsers.Add(userObj);
                db.SaveChanges();
                return("Ok");
            }
            catch (Exception cc)
            {
                throw cc;
            }
        }
Esempio n. 11
0
        public async Task <IActionResult> PostTableUser([FromBody] TableUser tableUser)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _context.tableUsers.Add(tableUser);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetTableUser", new { id = tableUser.id }, tableUser));
        }
Esempio n. 12
0
 public TableUser ValidateUser([FromBody] TableUser userObj)
 {
     try
     {
         string    encpass = Crypto.Hash(userObj.Password);
         TableUser tu      = db.TableUsers.Where(u => u.Username.Contains(userObj.Username) && u.Password.Contains(encpass)).FirstOrDefault();
         return(tu);
     }
     catch (Exception cc)
     {
         throw cc;
     }
 }
Esempio n. 13
0
        public async Task <IActionResult> Create([Bind("Id,Locked,PhoneNumber,PhoneChecked,DefaultUserLanguage,Password,RestPasswort,CreatedAtUtc,IsDemoUser,IsAdmin,Firstname,Lastname,Street,PostalCode,City")]
                                                 TableUser tableUser)
        {
            if (ModelState.IsValid)
            {
                _context.Add(tableUser);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }

            return(View(tableUser));
        }
Esempio n. 14
0
        public static ExEmailRegistration GetRegistrationEmail(TableUser user)
        {
            var url = $"{Constants.ServiceClientEndPointWithApiPrefix}UserValidateEMail/{user.Id}/{user.RestPasswort}";

            Logging.Log.LogInfo($"SendCheckEMail: {url}");

            return(new ExEmailRegistration
            {
                Message = "Um die Registrierung abzuschließen, drücken Sie den folgenden Link:",
                ApproveLink = url,
                AlternativeText = $"Alternativ kopieren sie den folgenden Link und rufen Sie ihn einem Browser ihrer Wahl auf: {url}",
            });
        }
Esempio n. 15
0
        private async Task OpenDialog(TableUser tableUser)
        {
            var parameters = new DialogParameters()
            {
                { "User", tableUser },
            };
            var dialog = this.DialogService.Show <UserRolesDialog>("User Roles", parameters);
            var result = await dialog.Result;

            if (!result.Cancelled)
            {
                this.Dispatcher.Dispatch(new GetUsersAction());
            }
        }
Esempio n. 16
0
        public static ExEmailResetPassword GetPasswordResetEmail(TableUser data)
        {
            //Einladung versenden
            var url = $"{Constants.ServiceClientEndPointWithApiPrefix}UserResetPassword/{data.Id}/{data.RestPasswort}";

            Logging.Log.LogInfo($"Send StartResetPassword: {url}");

            return(new ExEmailResetPassword
            {
                Message = "Um ihr Passwort zurück zu setzen, drücken Sie den folgenden Link:",
                ApproveLink = url,
                AlternativeText = $"Alternativ kopieren sie den folgenden Link und rufen Sie ihn einem Browser ihrer Wahl auf: {url}",
            });
        }
Esempio n. 17
0
        public bool createUser(User userToCreate)
        {
            try
            {
                TableUser createdUser = new TableUser(userToCreate.name, userToCreate.surname, userToCreate.birthday, userToCreate.fiscalCode, userToCreate.email, userToCreate.password, false);
                this.connection.users.InsertOnSubmit(createdUser);

                connection.SubmitChanges();
            }
            catch (Exception e)
            {
                return(false);
            }
            return(true);
        }
Esempio n. 18
0
        private async Task LoadAsync(TableUser user)
        {
            var userName = await _userManager.GetUserNameAsync(user);

            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            Username = userName;

            Input = new InputModel
            {
                PhoneNumber          = phoneNumber,
                RegistrationDateTime = user.RegistrationDateTime,
                LastLoginDateTime    = user.LastLoginDateTime
            };
        }
Esempio n. 19
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new TableUser {
                    UserName = Input.Email, Email = Input.Email, RegistrationDateTime = DateTime.Now, IsEnabled = true
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Esempio n. 20
0
        public async Task <ManageInfoViewModel> GetManageInfo(string returnUrl, bool generateState = false)
        {
            TableUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

            if (user == null)
            {
                return(null);
            }

            List <UserLoginInfoViewModel> logins = new List <UserLoginInfoViewModel>();

            foreach (TableUserLogin linkedAccount in user.Logins)
            {
                logins.Add(new UserLoginInfoViewModel
                {
                    LoginProvider = linkedAccount.LoginProvider,
                    ProviderKey   = linkedAccount.ProviderKey
                });
            }

            if (user.PasswordHash != null)
            {
                logins.Add(new UserLoginInfoViewModel
                {
                    LoginProvider = LocalLoginProvider,
                    ProviderKey   = user.UserName,
                });
            }

            return(new ManageInfoViewModel
            {
                LocalLoginProvider = LocalLoginProvider,
                Email = user.UserName,
                Logins = logins,
                ExternalLoginProviders = GetExternalLogins(returnUrl, generateState)
            });
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (UserManager <IdentityUser> userManager = _userManagerFactory())
            {
                TableUser user = await userManager.FindAsync(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

                ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
                                                                                     context.Options.AuthenticationType);

                ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
                                                                                       CookieAuthenticationDefaults.AuthenticationType);

                AuthenticationProperties properties = CreateProperties(user.UserName);
                AuthenticationTicket     ticket     = new AuthenticationTicket(oAuthIdentity, properties);
                context.Validated(ticket);
                context.Request.Context.Authentication.SignIn(cookiesIdentity);
            }
        }
Esempio n. 22
0
		//Insertion des DATS USER
		public string InsertDataUser(string user_AndsoftUser, string user_TransicsUser,string user_Password, string user_UsePartic)
		{
			try
			{
				string dbPath = System.IO.Path.Combine(Environment.GetFolderPath
					(Environment.SpecialFolder.Personal), "ormDMS.db3");
				var db = new SQLiteConnection(dbPath);
				TableUser item = new TableUser();

				item.user_AndsoftUser =  user_AndsoftUser;
				item.user_TransicsUser = user_TransicsUser;
				item.user_Password = user_Password;
				item.user_UsePartic = user_UsePartic;
				db.Insert(item);

				return "Insertion" +user_AndsoftUser+" réussite";
			}
			catch (Exception ex)
			{
				Insights.Report(ex);
				return "Erreur : " + ex.Message;

			}
		}
Esempio n. 23
0
        public async Task <Tuple <string, TableInfo> > UpdateTableInfoAsync(string oldTableName, TableInfo oldTableInfo)
        {
            ConvertInfo converter = null;

            if (StringUtils.EqualsIgnoreCase(TableAdministrator.OldTableName, oldTableName))
            {
                var table = new TableAdministrator(_databaseManager);
                converter = table.Converter;
            }
            else if (StringUtils.EqualsIgnoreCase(TableAdministratorsInRoles.OldTableName, oldTableName))
            {
                var table = new TableAdministratorsInRoles(_databaseManager);
                converter = table.Converter;
            }
            else if (ListUtils.ContainsIgnoreCase(TableChannel.OldTableNames, oldTableName))
            {
                var table = new TableChannel(_databaseManager);
                converter = table.Converter;
            }
            else if (ListUtils.ContainsIgnoreCase(TableChannelGroup.OldTableNames, oldTableName))
            {
                var table = new TableChannelGroup(_databaseManager);
                converter = table.Converter;
            }
            else if (StringUtils.EqualsIgnoreCase(TableConfig.OldTableName, oldTableName))
            {
                var table = new TableConfig(_databaseManager);
                converter = table.Converter;
            }
            else if (StringUtils.EqualsIgnoreCase(TableContentCheck.OldTableName, oldTableName))
            {
                var table = new TableContentCheck(_databaseManager);
                converter = table.Converter;
            }
            else if (ListUtils.ContainsIgnoreCase(TableContentGroup.OldTableNames, oldTableName))
            {
                var table = new TableContentGroup(_databaseManager);
                converter = table.Converter;
            }
            else if (StringUtils.EqualsIgnoreCase(TableDbCache.OldTableName, oldTableName))
            {
                var table = new TableDbCache(_databaseManager);
                converter = table.Converter;
            }
            else if (StringUtils.EqualsIgnoreCase(TableErrorLog.OldTableName, oldTableName))
            {
                converter = TableErrorLog.Converter;
            }
            else if (StringUtils.EqualsIgnoreCase(TableLog.OldTableName, oldTableName))
            {
                var table = new TableLog(_databaseManager);
                converter = table.Converter;
            }
            else if (StringUtils.EqualsIgnoreCase(TablePermissionsInRoles.OldTableName, oldTableName))
            {
                var table = new TablePermissionsInRoles(_databaseManager);
                converter = table.Converter;
            }
            else if (ListUtils.ContainsIgnoreCase(TableRelatedField.OldTableNames, oldTableName))
            {
                var table = new TableRelatedField(_databaseManager);
                converter = table.Converter;
            }
            else if (ListUtils.ContainsIgnoreCase(TableRelatedFieldItem.OldTableNames, oldTableName))
            {
                var table = new TableRelatedFieldItem(_databaseManager);
                converter = table.Converter;
            }
            else if (StringUtils.EqualsIgnoreCase(TableRole.OldTableName, oldTableName))
            {
                var table = new TableRole(_databaseManager);
                converter = table.Converter;
            }
            else if (ListUtils.ContainsIgnoreCase(TableSite.OldTableNames, oldTableName))
            {
                var table = new TableSite(_databaseManager);
                converter = table.Converter;
            }
            else if (ListUtils.ContainsIgnoreCase(TableSiteLog.OldTableNames, oldTableName))
            {
                var table = new TableSiteLog(_databaseManager);
                converter = table.Converter;
            }
            else if (ListUtils.ContainsIgnoreCase(TableSitePermissions.OldTableNames, oldTableName))
            {
                var table = new TableSitePermissions(_databaseManager);
                converter = table.Converter;
            }
            else if (StringUtils.EqualsIgnoreCase(TableTableStyle.OldTableName, oldTableName))
            {
                var table = new TableTableStyle(_databaseManager);
                converter = table.Converter;
            }
            else if (StringUtils.EqualsIgnoreCase(TableContentTag.OldTableName, oldTableName))
            {
                var table = new TableContentTag(_databaseManager);
                converter = table.Converter;
            }
            else if (ListUtils.ContainsIgnoreCase(TableTemplate.OldTableNames, oldTableName))
            {
                var table = new TableTemplate(_databaseManager);
                converter = table.Converter;
            }
            else if (ListUtils.ContainsIgnoreCase(TableTemplateLog.OldTableNames, oldTableName))
            {
                var table = new TableTemplateLog(_databaseManager);
                converter = table.Converter;
            }
            else if (StringUtils.EqualsIgnoreCase(TableUser.OldTableName, oldTableName))
            {
                var table = new TableUser(_databaseManager);
                converter = table.Converter;
            }

            return(await GetNewTableInfoAsync(oldTableName, oldTableInfo, converter));
        }
 public HelpNotification(TableUser sentBy, HelpNotificationStatus status, string subjectId)
 {
     SentBy    = sentBy;
     Status    = status;
     SubjectId = subjectId;
 }
Esempio n. 25
0
 public NotificationAvatarViewModel(TableUser user)
 {
     User = user;
     User.PropertyChanged += UpdateUserProperties;
     Messenger.Default.Register <CompletedClassification>(this, OnCompletedClassification, $"{user.Name}_AddCompletedClassification");
 }
Esempio n. 26
0
 public static UserName Read(ISqDataRecordReader record, TableUser table)
 {
     return(new UserName(id: table.UserId.Read(record), firstName: table.FirstName.Read(record), lastName: table.LastName.Read(record)));
 }
Esempio n. 27
0
 public static TableColumn[] GetColumns(TableUser table)
 {
     return(new TableColumn[] { table.UserId, table.FirstName, table.LastName });
 }
Esempio n. 28
0
 public static TableColumn[] GetColumns(TableUser table)
 {
     return(new TableColumn[] { table.Version, table.ModifiedAt });
 }
Esempio n. 29
0
 public static AuditData ReadOrdinal(ISqDataRecordReader record, TableUser table, int offset)
 {
     return(new AuditData(version: table.Version.Read(record, offset), modifiedAt: table.ModifiedAt.Read(record, offset + 1)));
 }
Esempio n. 30
0
 public static AuditData Read(ISqDataRecordReader record, TableUser table)
 {
     return(new AuditData(version: table.Version.Read(record), modifiedAt: table.ModifiedAt.Read(record)));
 }
Esempio n. 31
0
 /// <summary>
 ///     Bestätigungs-Token senden ...
 /// </summary>
 /// <param name="user">User Daten</param>
 /// <returns></returns>
 private async Task <bool> SendPassword(TableUser user, string password, bool isNewUser = false)
 {
     return(!string.IsNullOrWhiteSpace(Common.SendSMS(user.PhoneNumber, "Dein Passwort für meinschaufenster.at lautet: " + password)));
 }
Esempio n. 32
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
                });
            }
        }