コード例 #1
0
        private async Task EstablishUserData(NavigationParameters parameters)
        {
            // Check if user data has been provided in the parameters.
            if (parameters.ContainsKey("userData"))
            {
                _appUserData = parameters["userData"] as AppUserData;
            }

            if (_appUserData == null)
            {
                if (StaticUserDataStore.UserData != null)
                {
                    // This copies the memory-based user data, thus ensuring that
                    // the Save/Back functionality works.
                    // If this is directly set to the memory-based store, changes will
                    // be automatically "saved".
                    var memoryAppUserData = StaticUserDataStore.UserData;
                    _appUserData = new AppUserData();
                    foreach (var runtimeProperty in memoryAppUserData.GetType().GetRuntimeProperties())
                    {
                        var memoryAppData = runtimeProperty.GetValue(memoryAppUserData);
                        runtimeProperty.SetValue(_appUserData, memoryAppData);
                    }
                }
            }

            // Otherwise, load app user data from file path.
            if (_appUserData == null)
            {
                // This loads the data from persistent storage into a new instance
                // of app user data.
                _appUserData = new AppUserData();
                _appUserData = await LoadAppUserDataFromFileAsync(StaticUserDataStore.UserFileName);
            }
        }
コード例 #2
0
        /// <summary>
        /// Get profile if <see cref="App.getProfileInfo" didn't have time to load./>
        /// </summary>
        /// <returns>Task.</returns>
        async Task getProfile()
        {
            var profile = await DataAccess.GetProfileInfo(PlatformServices.Preferences.UserLogin);

            AppUserData.SetProfileData(PlatformServices, profile);
            IsStudent = AppUserData.UserType == UserTypeEnum.Student;
        }
コード例 #3
0
 void resetData()
 {
     _services.Preferences.ResetPrefs();
     AppUserData.Clear();
     DataAccess.ResetData();
     _services.Navigation.OpenLogin();
 }
コード例 #4
0
        void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
        {
            MainContext context = DependencyResolver.Current.GetService <MainContext>();

            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                if (!filterContext.ActionDescriptor.GetCustomAttributes(false).ToList().Any(x => x is AllowAnonymousAttribute))
                {
                    filterContext.Result = new HttpUnauthorizedResult();
                    return;
                }
                if (_unknownUserId == null)
                {
                    lock (_lockObject)
                    {
                        if (_unknownUserId == null)
                        {
                            _unknownUserId = UserHelper.GetUnknownUserId();
                        }
                    }
                }
                context.PersonId = _unknownUserId.Value;
                return;
            }

            AppUserData userData = UserHelper.GetUserData();

            context.PersonId        = userData.Id;
            context.Functionalities = userData.Functionalities;
        }
コード例 #5
0
        void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
        {
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                throw new AuthorizationException(ErrorResource.NoLoginAdded);
            }

            AppUserData userData = UserHelper.GetUserData();

            if (!userData.IsActive)
            {
                throw new NotActiveException(ErrorResource.AdAuthorizationNotActiveErrorText);
            }
            MainContext context = DependencyResolver.Current.GetService <MainContext>();

            context.PersonId        = userData.Id;
            context.Functionalities = userData.Functionalities;

            IAppUserService userService = DependencyResolver.Current.GetService <IAppUserService>();

            if (userData.Login == null || userData.Login.Length == 0 || userService.GetUserDataByAdLogin(userData.Login) == null)
            {
                throw new AuthorizationException(userData.Login);
            }
        }
コード例 #6
0
 private async void OpenSelectClinicalAreaPage(AppUserData currentAppUserData)
 {
     var navigationParameters = new NavigationParameters {
         { "userData", currentAppUserData }
     };
     await _navigationService.NavigateAsync("SelectClinicalAreaPage", navigationParameters);
 }
コード例 #7
0
ファイル: App.cs プロジェクト: TTcoinDeveloper/HomeSchool
        /// <summary>
        /// Gets user's profile info if authorized.
        /// </summary>
        /// <returns>Task.</returns>
        async Task getProfileInfo()
        {
            try {
                if (!_services.Preferences.IsLoggedIn)
                {
                    return;
                }

                var username = _services.Preferences.UserLogin;

                if (string.IsNullOrEmpty(username))
                {
                    return;
                }

                var profile = await DataAccess.GetProfileInfo(username);

                AppUserData.SetLoginData(_services, _services.Preferences.UserId, username);
                AppUserData.SetProfileData(_services, profile);
                _services.Preferences.GroupName = profile?.GroupName;
                _services.Preferences.Avatar    = profile?.Avatar;
            } catch (Exception ex) {
                AppLogs.Log(ex);
            }
        }
コード例 #8
0
        public static void RefreshUserData()
        {
            string userName = HttpContext.Current.User.Identity.Name;

            if (userName.IsNullOrEmpty())
            {
                return;
            }
            AppUserData userData = HttpContext.Current.Session[SessionVariableNames.AppUserData] as AppUserData;

            if (userData != null && userData.UserName == userName)
            {
                IAppUserService userService = DependencyResolver.Current.GetService <IAppUserService>();
#if DEBUG
                userData = userService.GetFirstUser();
#else
                userData = userService.GetUserDataByAdLogin(userName);
#endif
                if (userData == null)
                {
                    throw new AuthorizationException(ErrorResource.NoLoginAdded);
                }
                HttpContext.Current.Session[SessionVariableNames.AppUserData] = userData;
            }
        }
コード例 #9
0
 protected UpdaterManager(IMessageUIManager message, IFileManager file, AppUserData data, IAppInstanceData instanceData)
 {
     Message      = message ?? throw new ArgumentNullException(nameof(message));
     File         = file ?? throw new ArgumentNullException(nameof(file));
     Data         = data ?? throw new ArgumentNullException(nameof(data));
     InstanceData = instanceData ?? throw new ArgumentNullException(nameof(instanceData));
 }
コード例 #10
0
        /// <summary>
        /// Gets profile data by username and user's ID and saves it.
        /// </summary>
        /// <param name="username">Username.</param>
        /// <returns>Task.</returns>
        async Task <UserProfileModel> getProfileData(string username)
        {
            var userProfile = await DataAccess.GetProfileInfo(username);

            AppUserData.SetProfileData(_services, userProfile);
            return(userProfile);
        }
コード例 #11
0
        public static IList <FunctionalityType> GetUserFunctionalities()
        {
            AppUserData userData = GetUserData();

            IList <FunctionalityType> userFunctionalities = userData.Functionalities;

            return(userFunctionalities);
        }
コード例 #12
0
 void changeServer(ServerPageModel server)
 {
     Servers.SetCurrent(server.Address);
     _services.Preferences.IsLoggedIn = false;
     AppUserData.Clear();
     DataAccess.ResetData();
     toggleServer(server);
 }
コード例 #13
0
        public override global::System.Data.DataSet Clone()
        {
            AppUserData cln = ((AppUserData)(base.Clone()));

            cln.InitVars();
            cln.SchemaSerializationMode = this.SchemaSerializationMode;
            return(cln);
        }
コード例 #14
0
 public void SetProfileProfessorData()
 {
     AppUserData.SetProfileData(_mocked, _profile);
     Assert.AreEqual(_name, AppUserData.Name);
     Assert.AreEqual(_avatar, AppUserData.Avatar);
     Assert.AreEqual(_groupId, AppUserData.GroupId);
     Assert.AreEqual(_groupName, AppUserData.GroupName);
     Assert.AreEqual(true, AppUserData.IsProfileLoaded);
     Assert.AreEqual(UserTypeEnum.Professor, AppUserData.UserType);
 }
コード例 #15
0
        /// <summary>
        /// Gets user data (username and user's id) by provided credentials and saves it.
        /// </summary>
        /// <returns><see cref="UserModel"/> on success, <code>null</code> otherwise.</returns>
        async Task <UserModel> loginRequest()
        {
            var userLogin = await DataAccess.Login(Username, Password);

            if (userLogin != null)
            {
                AppUserData.SetLoginData(_services, userLogin.UserId, userLogin.Username);
            }

            return(userLogin);
        }
コード例 #16
0
        private async void SelectClinicalArea(AppUserData currentAppUserData)
        {
            currentAppUserData.ClinicalArea = new ClinicalArea
            {
                Id   = Id,
                Name = Name
            };
            NavigationParameters navigationParameters = new NavigationParameters();

            navigationParameters.Add("userData", currentAppUserData);
            await _navigationService.GoBackAsync(navigationParameters);
        }
コード例 #17
0
        public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(global::System.Xml.Schema.XmlSchemaSet xs)
        {
            AppUserData ds = new AppUserData();

            global::System.Xml.Schema.XmlSchemaComplexType type     = new global::System.Xml.Schema.XmlSchemaComplexType();
            global::System.Xml.Schema.XmlSchemaSequence    sequence = new global::System.Xml.Schema.XmlSchemaSequence();
            global::System.Xml.Schema.XmlSchemaAny         any      = new global::System.Xml.Schema.XmlSchemaAny();
            any.Namespace = ds.Namespace;
            sequence.Items.Add(any);
            type.Particle = sequence;
            global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
            if (xs.Contains(dsSchema.TargetNamespace))
            {
                global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
                global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
                try {
                    global::System.Xml.Schema.XmlSchema schema = null;
                    dsSchema.Write(s1);
                    for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext();)
                    {
                        schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
                        s2.SetLength(0);
                        schema.Write(s2);
                        if ((s1.Length == s2.Length))
                        {
                            s1.Position = 0;
                            s2.Position = 0;
                            for (; ((s1.Position != s1.Length) &&
                                    (s1.ReadByte() == s2.ReadByte()));)
                            {
                                ;
                            }
                            if ((s1.Position == s1.Length))
                            {
                                return(type);
                            }
                        }
                    }
                }
                finally {
                    if ((s1 != null))
                    {
                        s1.Close();
                    }
                    if ((s2 != null))
                    {
                        s2.Close();
                    }
                }
            }
            xs.Add(dsSchema);
            return(type);
        }
コード例 #18
0
        public async void OnNavigatingTo(NavigationParameters parameters)
        {
            // Check if user data has been provided in the parameters.
            if (parameters.ContainsKey("userData"))
            {
                _appUserData = parameters["userData"] as AppUserData;
            }

            if (_appUserData == null)
            {
                // Check if user data is already in memory
                if (StaticUserDataStore.UserData != null)
                {
                    // This copies the memory-based user data, thus ensuring that
                    // the Save/Back functionality works.
                    // If this is directly set to the memory-based store, changes will
                    // be automatically "saved".
                    var memoryAppUserData = StaticUserDataStore.UserData;
                    _appUserData = new AppUserData();
                    foreach (var runtimeProperty in memoryAppUserData.GetType().GetRuntimeProperties())
                    {
                        var memoryAppData = runtimeProperty.GetValue(memoryAppUserData);
                        runtimeProperty.SetValue(_appUserData, memoryAppData);
                    }
                }
            }

            // Otherwise, load app user data from file path.
            if (_appUserData == null)
            {
                // This loads the data from persistent storage into a new instance
                // of app user data.
                _appUserData = new AppUserData();
                _appUserData = await LoadAppUserDataFromFileAsync(StaticUserDataStore.UserFileName);
            }

            // If no data has been specified, then create new app user data.
            if (_appUserData == null)
            {
                // This simply creates a new app user data.
                _appUserData = new AppUserData();
            }

            // Load the data for the view model properties.
            Forename                = _appUserData?.Forename;
            Surname                 = _appUserData?.Surname;
            Designation             = _appUserData?.Designation;
            CurrentClinicalAreaName = _appUserData?.ClinicalArea?.Name;

            // Generate the command to select a clinial area.
            SelectClinicalAreaCommand = new DelegateCommand(() => OpenSelectClinicalAreaPage(_appUserData));
        }
コード例 #19
0
        public void SetProfileStudentData()
        {
            var profile = _profile;

            profile.UserType = _userTypeStudent;
            AppUserData.SetProfileData(_mocked, profile);
            Assert.AreEqual(_name, AppUserData.Name);
            Assert.AreEqual(_avatar, AppUserData.Avatar);
            Assert.AreEqual(_groupId, AppUserData.GroupId);
            Assert.AreEqual(_groupName, AppUserData.GroupName);
            Assert.AreEqual(true, AppUserData.IsProfileLoaded);
            Assert.AreEqual(UserTypeEnum.Student, AppUserData.UserType);
        }
コード例 #20
0
 public void ClearTest()
 {
     AppUserData.SetProfileData(_mocked, _profile);
     AppUserData.Clear();
     Assert.AreEqual(0, AppUserData.UserId);
     Assert.AreEqual(null, AppUserData.Name);
     Assert.AreEqual(0, AppUserData.GroupId);
     Assert.AreEqual(null, AppUserData.Avatar);
     Assert.AreEqual(null, AppUserData.Username);
     Assert.AreEqual(null, AppUserData.GroupName);
     Assert.AreEqual(true, AppUserData.IsProfileLoaded);
     Assert.AreEqual(UserTypeEnum.Student, AppUserData.UserType);
 }
コード例 #21
0
        void IAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
        {
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new HttpUnauthorizedResult();
                return;
            }
            AppUserData appUserData = UserHelper.GetUserData();

            if (!appUserData.Roles.Any(x => x == Dictionaries.AppRoleType.Administrator))
            {
                throw new AuthorizationException(ErrorResource.AccessDenied);
            }
        }
コード例 #22
0
        public static AppUserData GetUserData(bool force = false, string userName = "")
        {
            if (HttpContext.Current == null)
            {
                return(null);
            }
            if (userName.IsNullOrEmpty())
            {
                userName = HttpContext.Current.User.Identity.Name;
            }
            if (userName.IsNullOrEmpty())
            {
                throw new AuthorizationException(ErrorResource.NoLoginAdded);
            }
            AppUserData userData = null;

            userData = HttpContext.Current.Session?[SessionVariableNames.AppUserData] as AppUserData;

#if DEBUG
            bool isTheSameUserName = true;
#else
            bool isTheSameUserName = false;
            if (userData != null)
            {
                isTheSameUserName = userData.UserName == userName;
            }
#endif
            if (userData == null || !isTheSameUserName || force)
            {
                IAppUserService userService = DependencyResolver.Current.GetService <IAppUserService>();
#if DEBUG
                userData = userService.GetFirstUser();
#else
                //var principalContext = new PrincipalContext(ContextType.Domain);
                userData = userService.GetUserDataByAdLogin(userName);
#endif
                if (userData == null)
                {
                    throw new AuthorizationException(ErrorResource.NoLoginAdded);
                }
                if (HttpContext.Current.Session != null)
                {
                    HttpContext.Current.Session[SessionVariableNames.AppUserData] = userData;
                }
            }

            return(userData);
        }
コード例 #23
0
        /// <summary>
        /// Gets user data (username and user's id) by provided credentials and saves it.
        /// </summary>
        /// <returns><see cref="UserModel"/> on success, <code>null</code> otherwise.</returns>
        async Task <UserModel> loginRequest()
        {
            var userLogin = await DataAccess.Login(Username, Password);

            if (_services.Preferences.Server == Servers.EduCatsAddress)
            {
                if (userLogin != null)
                {
                    var jwt = new
                    {
                        password = Password,
                        userName = Username,
                    };
                    var body           = JsonController.ConvertObjectToJson(jwt);
                    var httpWebRequest = (HttpWebRequest)WebRequest.Create(Links.LoginTestServer);
                    httpWebRequest.ContentType = "application/json";
                    httpWebRequest.Method      = "POST";
                    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                    {
                        string json = body;

                        streamWriter.Write(json);
                        streamWriter.Flush();
                        streamWriter.Close();
                    }
                    var tok          = "";
                    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                    {
                        string line = "";
                        while ((line = streamReader.ReadLine()) != null)
                        {
                            tok += line;
                        }
                    }
                    var token = JsonConvert.DeserializeObject <TokenModel>(tok);
                    _services.Preferences.AccessToken = token.Token;
                    SecondUserModel userLoginTest = await DataAccess.LoginTest(Username, Password);

                    userLogin.UserId   = userLoginTest.Id;
                    userLogin.Username = userLoginTest.Username;
                }
            }
            AppUserData.SetLoginData(_services, userLogin.UserId, userLogin.Username);
            return(userLogin);
        }
コード例 #24
0
        public async Task <IActionResult> UpdateUser(long id, [FromBody] AppUserData userData)
        {
            if (ModelState.IsValid)
            {
                UserDetails userInfo = userData.User;
                userInfo.UserDetailsID   = id;
                userInfo.LastUpdatedDate = DateTime.UtcNow;
                context.Update(userInfo);
                context.SaveChanges();
                await emailSender.SendEmailAsync("*****@*****.**", "User Account Updated", "User account has been updated in <a href='" + HttpContext.Request.Protocol
                                                 + HttpContext.Request.Host + "'>digital kilinik</a>");

                return(Ok());
            }
            else
            {
                return(BadRequest(ModelState));
            }
        }
コード例 #25
0
        /// <summary>
        ///     Головний метод
        /// </summary>
        /// <param name="args">Аргументи запуску</param>
        public static void Main(string[] args)
        {
            var host          = CreateWebHostBuilder(args).Build();
            var isDevelopment = HostingEnvironment.IsDevelopment();

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;
                Log.Information("{Info}", "Застосування міграцій");
                services.GetService <ApplicationDbContext>().ApplyMigrationsAsync().Wait();
                Log.Information("{Info}", "Додавання данних");
                AppRoleData.Seed(services).Wait();
                AppUserData.Seed(services, isDevelopment).Wait();
                services.GetService <ApplicationDbContext>().EnsureSeededAsync(isDevelopment).Wait();
                services.GetService <ApplicationDbContext>().EnsureSeededAfterAsync(isDevelopment).Wait();
            }
            Log.Information("{Info}", "Запуск сервісу");
            host.Run();
        }
コード例 #26
0
ファイル: AuthSvc.cs プロジェクト: TaniaShevchuk/Momento-API
        public AppResponse <User> AuthenticateUser(string email, string password)
        {
            var user = new AppUserData(settings).GetUser();

            return(new AppResponse <User>(true, user));
        }
コード例 #27
0
 public void SetProfileDataNullTest()
 {
     AppUserData.SetProfileData(_mocked, null);
     Assert.AreEqual(false, AppUserData.IsProfileLoaded);
 }
コード例 #28
0
 public void SetLoginDataTest()
 {
     AppUserData.SetLoginData(_mocked, _userId, _username);
     Assert.AreEqual(_userId, AppUserData.UserId);
     Assert.AreEqual(_username, AppUserData.Username);
 }
コード例 #29
0
    public AppViewModel(IUpdaterManager updater, IMessageUIManager message, IFileManager file, AppUIManager ui, AppUserData data)
    {
        // Set properties
        Updater = updater ?? throw new ArgumentNullException(nameof(updater));
        Message = message ?? throw new ArgumentNullException(nameof(message));
        File    = file ?? throw new ArgumentNullException(nameof(file));
        UI      = ui ?? throw new ArgumentNullException(nameof(ui));
        Data    = data ?? throw new ArgumentNullException(nameof(data));

        // Flag that the startup has begun
        IsStartupRunning = true;

        // Check if the application is running as administrator
        try
        {
            IsRunningAsAdmin = WindowsHelpers.RunningAsAdmin;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error");
            IsRunningAsAdmin = false;
        }

        AppTitle = IsRunningAsAdmin ? Resources.AppNameAdmin : Resources.AppName;

        LoadOperation = new Operation(() => IsLoading = true, () => IsLoading = false);

        // Create locks
        SaveUserDataAsyncLock      = new AsyncLock();
        MoveBackupsAsyncLock       = new AsyncLock();
        AdminWorkerAsyncLock       = new AsyncLock();
        OnRefreshRequiredAsyncLock = new AsyncLock();

        // Create commands
        RestartAsAdminCommand        = new AsyncRelayCommand(RestartAsAdminAsync);
        RequestRestartAsAdminCommand = new AsyncRelayCommand(RequestRestartAsAdminAsync);

        // Read the game manager configuration
        var gameConfig = Files.Games;

        // Set up the games manager
        GamesManager = JsonConvert.DeserializeObject <AppGamesManager>(gameConfig, new SimpleTypeConverter())
                       ?? throw new InvalidOperationException("Deserialized game manager is null");
    }
コード例 #30
0
 public RCPWindowDialogBaseManager(AppUserData data)
 {
     Data = data ?? throw new ArgumentNullException(nameof(data));
 }