예제 #1
0
        /// <summary>
        /// Tworzy nowego usera w oparciu o json'a zwrotnego z autentykatora, w przypadku błędu zrobic wyjatek
        /// </summary>
        /// <param name="provider">Nazwa providera autentykacji</param>
        /// <param name="jsonResponse">Token zawierajacy dane do stworzenia uzytkownika</param>
        /// <returns>Zwraca stworzone konto użytkownika</returns>
        public UserPublic Create(AuthenticationProvider provider, string jsonResponse)
        {
            try
            {
                JObject    jsonParsed  = JObject.Parse(jsonResponse);
                UserPublic userAccount = new UserPublic();
                switch (provider)
                {
                case AuthenticationProvider.Google:
                    userAccount.FirstName = (string)jsonParsed["given_name"];
                    userAccount.LastName  = (string)jsonParsed["family_name"];
                    userAccount.OAuthID   = (string)jsonParsed["sub"];
                    break;

                case AuthenticationProvider.Microsoft:
                    userAccount.FirstName = (string)jsonParsed["givenName"];
                    userAccount.LastName  = (string)jsonParsed["surname"];
                    userAccount.OAuthID   = (string)jsonParsed["id"];
                    break;

                default:
                    throw new ArgumentException("Problem ze stworzeniem uzytkownika", nameof(provider));
                }

                return(userAccount);
            }
            catch
            {
                throw;
                //TODO: Zalogowac przypadek
            }
        }
예제 #2
0
        private void SeedDefaultUsersPublic(IApplicationBuilder app)
        {
            var scopeFactory = app.ApplicationServices.GetRequiredService <IServiceScopeFactory>();

            using (var scope = scopeFactory.CreateScope())
            {
                var dbContext = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
                if (dbContext.UserPublic.FirstOrDefault(u => u.FirstName == "PublicDenis") == null)
                {
                    UserPublic UsersPublicDenis = new UserPublic {
                        FirstName = "PublicDenis", LastName = "Popandopalo"
                    };
                    UserPublic UsersPublicDenis2 = new UserPublic {
                        FirstName = "PublicDenis2", LastName = "Popandopalo2"
                    };
                    UserPublic UsersPublicDenis3 = new UserPublic {
                        FirstName = "PublicDenis3", LastName = "Popandopalo3"
                    };
                    UserPublic UsersPublicDenis4 = new UserPublic {
                        FirstName = "PublicDenis4", LastName = "Popandopalo4"
                    };
                    UserPublic UsersPublicDenis5 = new UserPublic {
                        FirstName = "PublicDenis5", LastName = "Popandopalo5"
                    };

                    dbContext.UserPublic.Add(UsersPublicDenis);
                    dbContext.UserPublic.Add(UsersPublicDenis2);
                    dbContext.UserPublic.Add(UsersPublicDenis3);
                    dbContext.UserPublic.Add(UsersPublicDenis4);
                    dbContext.UserPublic.Add(UsersPublicDenis5);

                    dbContext.SaveChanges();
                }
            }
        }
예제 #3
0
        public void Convert_ConvertsExistingServiceModelToEntity_ReturnsConvertedEntity()
        {
            // ARRANGE
            DbContextOptions <TestDatabaseContext> options = new DbContextOptionsBuilder <TestDatabaseContext>()
                                                             .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                                                             .Options;
            IDatabaseContext dbContext = new TestDatabaseContext(options);

            User user = new User()
            {
                ID        = 1,
                FirstName = "Johhny",
                LastName  = "Test",
                OAuthID   = "12345"
            };

            dbContext.Users.Add(user);
            dbContext.SaveChanges();

            UserConverter converter  = new UserConverter(dbContext);
            UserPublic    userPublic = new UserPublic()
            {
                ID        = 1,
                FirstName = "Johhny",
                LastName  = "Test",
                OAuthID   = "12345"
            };

            // ACT
            User user2 = converter.Convert(userPublic);

            // ASSERT
            user2.Should().BeEquivalentTo <User>(user);
        }
예제 #4
0
        public int Update_User(UserPublic p)
        {
            Database cn = new Database();

            SqlParameter[] prams =
            {
                cn.MakeInParam("@Id",        SqlDbType.Int,        4, p.Id),
                cn.MakeInParam("@FirstName", SqlDbType.NVarChar, 100, p.FirstName),
                cn.MakeInParam("@LastName",  SqlDbType.NVarChar, 100, p.LastName),
                cn.MakeInParam("@Dob",       SqlDbType.DateTime,  20, p.Dob),
                cn.MakeInParam("@IsActive",  SqlDbType.Bit,        1, p.IsActive)
            };
            cn.RunProc("User_Update", prams);
            cn.Dispose();
            try
            {
                return((int)prams[0].Value);
            }
            catch (Exception)
            {
                return(1);
            }
            finally
            {
                cn.Close();
                cn.Dispose();
            }
        }
예제 #5
0
        /// <summary>
        /// Tworzy usera na podstawie otrzymanego tokenu
        /// </summary>
        private async Task UserinfoCall(string AccessToken)
        {
            // builds the  request
            Uri    userinfoRequestURI   = new Uri("https://www.googleapis.com/oauth2/v3/userinfo");
            string userinfoResponseText = "";
            // sends the request
            HttpWebRequest userinfoRequest = (HttpWebRequest)WebRequest.Create(userinfoRequestURI);

            userinfoRequest.Method = "GET";
            userinfoRequest.Headers.Add(string.Format(CultureInfo.InvariantCulture, "Authorization: Bearer {0}", AccessToken));
            userinfoRequest.ContentType = "application/x-www-form-urlencoded";
            userinfoRequest.Accept      = "Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";

            // gets the response
            WebResponse userinfoResponse = await userinfoRequest.GetResponseAsync().ConfigureAwait(false);

            using (StreamReader userinfoResponseReader = new StreamReader(userinfoResponse.GetResponseStream()))
            {
                // reads response body
                userinfoResponseText = await userinfoResponseReader.ReadToEndAsync().ConfigureAwait(false);
            }
            User = new UserAccountFactory().Create(AuthenticationProvider.Google, userinfoResponseText);
            GoogleAvatarDownloader googleAvatarDownloader = new GoogleAvatarDownloader(userinfoResponseText);
            await googleAvatarDownloader.GetAvatarAsync(CancellationToken.None).ConfigureAwait(false);

            return;
        }
예제 #6
0
        /// <summary>
        /// Dokonuje próby logowania, jeżeli zapisane jest poprzednie logowanie
        /// </summary>
        public async Task LoginOnStartup()
        {
            SettingsManager settingsManager = new SettingsManager();
            string          defaultProvider = settingsManager.LoadProvider();

            if (!string.IsNullOrEmpty(defaultProvider))
            {
                if (Enum.TryParse(typeof(AuthenticationProvider), defaultProvider, out object provider))
                {
                    IsAuthenticationButtonsEnabled = false;
                    AuthenticationProvider authProvider = (AuthenticationProvider)provider;

                    AuthenticationProcessor authentication = new AuthenticationProcessor();
                    UserPublic userAccount = await authentication.AuthenticateAsync(authProvider, mCancellationToken.Token).ConfigureAwait(false);

                    if (this.ValidateAccount(userAccount, authProvider))
                    {
                        await LoginUserPTM().ConfigureAwait(false);

                        await this.OpenMainWindowAsync().ConfigureAwait(false);

                        return;
                    }

                    IsAuthenticationButtonsEnabled = true;
                }
            }
            else
            {
                settingsManager.DeleteProvider();
            }

            // Jeśli nie udało się zweryfikować usera, to pokazujemy okno
            mContext.WindowManager.ActivateWindow(Identity);
        }
예제 #7
0
        /// <summary>
        /// Dokonuje logowania przy użyciu Microsoft (Oauth 2)
        /// </summary>
        public async Task AuthenticateWithMicrosoftAsync()
        {
            try
            {
                IsAuthenticationButtonsEnabled = false;
                AuthenticationProcessor authentication = new AuthenticationProcessor();
                UserPublic userAccount = await authentication.AuthenticateAsync(AuthenticationProvider.Microsoft, mCancellationToken.Token).ConfigureAwait(false);

                if (this.ValidateAccount(userAccount, AuthenticationProvider.Microsoft))
                {
                    await LoginUserPTM().ConfigureAwait(false);

                    await this.OpenMainWindowAsync().ConfigureAwait(false);
                }
            }
            catch (OperationCanceledException)
            {
                // do nothing
            }
            catch (Exception ex)
            {
                mContext.DialogBuilder.ErrorDialog((Application.Current.TryFindResource("IDS_LoginWindow_AuthenticationError") as string), ex);
            }
            finally
            {
                IsAuthenticationButtonsEnabled = true;
            }
        }
예제 #8
0
        public void UpdateUser_IDNotExist_Returns404()
        {
            // ARRANGE
            List <UserPublic> users = new List <UserPublic>
            {
                new UserPublic()
                {
                    ID = 1, FirstName = "Adam", LastName = "A", OAuthID = "12345"
                },
                new UserPublic()
                {
                    ID = 2, FirstName = "Ewa", LastName = "E", OAuthID = "23456"
                },
                new UserPublic()
                {
                    ID = 3, FirstName = "Daniel", LastName = "D", OAuthID = "34567"
                }
            };
            IUserRepository userRepository = new MemoryUserRepository(users);
            UserController  controller     = new UserController(userRepository);

            // ACT
            UserPublic user = new UserPublic()
            {
                ID = 4, FirstName = "Janusz", LastName = "J", OAuthID = "45678"
            };

            user.FirstName = "Karol";
            StatusCodeResult result = controller.UpdateUser(user) as StatusCodeResult;

            // ASSERT
            result.StatusCode.Should().Be(404);
        }
예제 #9
0
        public void Convert_ConvertsEntityToServiceModel_ReturnsConvertedModel()
        {
            // ARRANGE
            DbContextOptions <TestDatabaseContext> options = new DbContextOptionsBuilder <TestDatabaseContext>()
                                                             .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                                                             .Options;
            IDatabaseContext dbContext = new TestDatabaseContext(options);
            UserConverter    converter = new UserConverter(dbContext);
            User             user      = new User()
            {
                ID        = 1,
                FirstName = "Johhny",
                LastName  = "Test",
                OAuthID   = "12345"
            };

            // ACT
            UserPublic userPublic = converter.Convert(user);

            // ASSERT
            userPublic.Should().BeEquivalentTo <UserPublic>(new UserPublic()
            {
                ID        = 1,
                FirstName = "Johhny",
                LastName  = "Test",
                OAuthID   = "12345"
            });
        }
예제 #10
0
        public UserPublic GetUserById(int id)
        {
            UserPublic user = new UserPublic();
            Database   cn   = new Database();

            SqlParameter[] prams = { cn.MakeInParam("@UserID", SqlDbType.Int, 4, id), };
            try
            {
                cn.RunProc("User_GetById", prams, out SqlDataReader sqlDataReader);
                if (sqlDataReader.HasRows)
                {
                    if (sqlDataReader.Read())
                    {
                        user.Id        = (int)sqlDataReader["Id"];
                        user.FirstName = (string)sqlDataReader["FirstName"];
                        user.LastName  = (string)sqlDataReader["LastName"];
                        user.Dob       = (DateTime)sqlDataReader["Dob"];
                        user.IsActive  = (bool)sqlDataReader["IsActive"];
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error with GetUserById.\n" + ex);
            }

            return(user);
        }
예제 #11
0
        public void GetUserOAuth_OnExistingUser_ReturnsUser()
        {
            // ARRANGE
            DbContextOptions <TestDatabaseContext> options = new DbContextOptionsBuilder <TestDatabaseContext>()
                                                             .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                                                             .Options;
            IDatabaseContext dbContext  = new TestDatabaseContext(options);
            UserRepository   repository = new UserRepository(dbContext);
            User             user       = new User()
            {
                FirstName = "Jan",
                LastName  = "Kowalski",
                OAuthID   = "12345"
            };

            dbContext.Users.Add(user);

            dbContext.SaveChanges();

            // ACT
            UserPublic userPublic = repository.GetUserOAuth("12345");

            // ASSERT
            userPublic.Should().BeEquivalentTo(new UserPublic()
            {
                ID        = 1,
                FirstName = "Jan",
                LastName  = "Kowalski",
                OAuthID   = "12345"
            });
        }
예제 #12
0
        public void UpdateUser_UpdatesUser_ReturnsUserAndOk()
        {
            // ARRANGE
            List <UserPublic> users = new List <UserPublic>
            {
                new UserPublic()
                {
                    ID = 1, FirstName = "Adam", LastName = "A", OAuthID = "12345"
                },
                new UserPublic()
                {
                    ID = 2, FirstName = "Ewa", LastName = "E", OAuthID = "23456"
                },
                new UserPublic()
                {
                    ID = 3, FirstName = "Daniel", LastName = "D", OAuthID = "34567"
                }
            };
            IUserRepository userRepository = new MemoryUserRepository(users);
            UserController  controller     = new UserController(userRepository);

            // ACT
            UserPublic user = (controller.GetUser(1) as ObjectResult).Value as UserPublic;

            user.FirstName = "Karol";
            controller.UpdateUser(user);
            ObjectResult result = controller.GetUser(1) as ObjectResult;

            // ASSERT
            result.Value.Should().BeEquivalentTo(new UserPublic()
            {
                ID = 1, FirstName = "Karol", LastName = "A", OAuthID = "12345"
            });
            result.StatusCode.Should().Be(200);
        }
예제 #13
0
        /// <inheritdoc/>
        public UserPublic CreateUser(UserPublic User)
        {
            Ensure.ParamNotNull(User, nameof(User));

            mUsers.Add(User);

            return(User);
        }
예제 #14
0
        /// <summary>
        /// convert user in data base to user public for api
        /// </summary>
        /// <param name="elem"></param>
        /// <returns>return new user as public</returns>
        private async Task <UserPublic> createUserPublic(UserCustom elem)
        {
            UserPublic node = new UserPublic();

            node.Id          = elem.Id;
            node.Name        = elem.UserName;
            node.Email       = elem.Email;
            node.PhoneNumber = elem.PhoneNumber;
            node.Role        = (await _userManager.GetRolesAsync(elem))[0];
            return(node);
        }
예제 #15
0
        public UserPublic GetUserOAuth(string OAuthID)
        {
            UserPublic user = mUsers.FirstOrDefault(u => u.OAuthID == OAuthID);

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

            return(user);
        }
예제 #16
0
        /// <inheritdoc/>
        public UserPublic GetUser(int ID)
        {
            UserPublic user = mUsers.FirstOrDefault(u => u.ID == ID);

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

            return(user);
        }
예제 #17
0
        /// <summary>
        /// modify user information in database
        /// </summary>
        /// <param name="user"></param>
        private async Task SetUserInfoFromUserPublic(UserPublic user, UserCustom userData)
        {
            userData.UserName = user.Name;
            userData.Email    = user.Email;
            await _userManager.RemoveFromRoleAsync(userData, (await _userManager.GetRolesAsync(userData))[0]);

            await _userManager.AddToRoleAsync(userData, user.Role);

            await _userManager.UpdateAsync(userData);

            return;
        }
예제 #18
0
        public virtual IActionResult CreateUser([FromBody] UserPublic user)
        {
            Ensure.ParamNotNull(user, nameof(user));

            UserPublic createdUser = mRepository.CreateUser(user);

            if (createdUser == null)
            {
                return(base.NotFound());
            }

            return(base.Created($"/users/{createdUser.ID}", createdUser));
        }
예제 #19
0
        public UserPublic UpdateUser(UserPublic user)
        {
            UserPublic oldUser = mUsers.FirstOrDefault(u => u.ID == user.ID);

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

            oldUser.FirstName = user.FirstName;
            oldUser.LastName  = user.LastName;
            return(oldUser);
        }
예제 #20
0
        public void GetUser_OnNonExistingUser_ReturnsNull()
        {
            // ARRANGE
            DbContextOptions <TestDatabaseContext> options = new DbContextOptionsBuilder <TestDatabaseContext>()
                                                             .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                                                             .Options;
            IDatabaseContext dbContext  = new TestDatabaseContext(options);
            UserRepository   repository = new UserRepository(dbContext);

            // ACT
            UserPublic userPublic = repository.GetUser(1);

            // ASSERT
            userPublic.Should().BeNull();
        }
예제 #21
0
        public async Task AuthenticateAsync_OnGoogleRefreshToken_SuccessfulAuthentication()
        {
            // ARRANGE
            AuthenticationProcessor processor = new AuthenticationProcessor();
            CredentialsManager      manager   = new CredentialsManager(AuthenticationProvider.Google);

            manager.SaveToken("*TOKEN*");

            // ACT
            UserPublic account = await processor.AuthenticateAsync(AuthenticationProvider.Google, CancellationToken.None);

            // ASSERT
            account.Should().NotBeNull();

            manager.DeleteToken();
        }
예제 #22
0
        /// <inheritdoc/>
        public UserPublic UpdateUser(UserPublic user)
        {
            UserLogic     logic     = new UserLogic(mDBContext);
            UserConverter converter = new UserConverter(mDBContext);

            try
            {
                UserPublic updatedUser = converter.Convert(logic.Update(converter.Convert(user)));
                mDBContext.SaveChangesAsync(CancellationToken.None);
                return(updatedUser);
            }
            catch
            {
                return(null);
            }
        }
        private static void Main(string[] args)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;

            int id   = 0;
            var user = new UserPublic
            {
                FirstName = "ToanTest2",
                LastName  = "Nguyen",
                Dob       = DateTime.Now,
                IsActive  = true
            };
            UserBUS userBus = new UserBUS();

            try
            {
                //1.Insert
                // id = userBus.Insert_User(user);

                //2. Update
                //user.Id = 6;
                //id = userBus.Update_User(user);

                //Delete
                //user.Id = 5;
                //userBus.Delete_User(user);

                //Get All User as Table
                //  DataTable dbTable = userBus.All_User();

                //
                var userGetById = userBus.GetUserById(2);

                Console.WriteLine(userGetById.FirstName);
                // con.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
            }

            Console.WriteLine("Insert Success with ID:" + id.ToString());
            Console.ReadLine();
        }
예제 #24
0
        /// <inheritdoc/>
        public UserPublic CreateUser(UserPublic user)
        {
            UserLogic     logic     = new UserLogic(mDBContext);
            UserConverter converter = new UserConverter(mDBContext);

            try
            {
                User createdUser = logic.Create(converter.Convert(user));

                mDBContext.SaveChanges();

                return(converter.Convert(createdUser));
            }
            catch
            {
                return(null);
            }
        }
예제 #25
0
        public IActionResult GetUserOAuth(string OAuthID)
        {
            try
            {
                UserPublic user = mRepository.GetUserOAuth(OAuthID);

                if (user == null)
                {
                    return(base.NotFound());
                }

                return(base.Ok(user));
            }
            catch (Exception ex)
            {
                return(base.Problem(ex.Message));
            }
        }
예제 #26
0
        /// <inheritdoc/>
        public async Task <UserPublic> GetUserOAuth(string OAuthID)
        {
            UserPublic User = null;

            using (HttpClient httpClient = base.CreateClient())
            {
                HttpResponseMessage response = await httpClient.GetAsync(string.Format("/users/OAuth/{0}", OAuthID));

                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                    User = JsonConvert.DeserializeObject <UserPublic>(json);
                }
            }

            return(User);
        }
예제 #27
0
 /// <summary>
 /// Waliduje konto
 /// </summary>
 /// <param name="userAccount">Konto usera do zwalidowania</param>
 /// <param name="provider">Provider z którego pochodzi konto</param>
 private bool ValidateAccount(UserPublic userAccount, AuthenticationProvider provider)
 {
     // W przypadku, kiedy nie udało się zwalidować konta
     if (userAccount == null)
     {
         // Błąd logowania może być spowodowany wygaśnięciem refresh tokena - trzeba usunąć wpis
         CredentialsManager credentialsManager = new CredentialsManager(provider);
         credentialsManager.DeleteToken();
         return(false);
     }
     else
     {
         SettingsManager settingsManager = new SettingsManager();
         settingsManager.SaveProvider(provider);
         mAccountTemp = userAccount;
         return(true);
     }
 }
예제 #28
0
        /// <summary>
        /// Call AcquireToken - to acquire a token requiring user to sign-in
        /// </summary>
        private async Task AuthenticateWithMicrosoft(CancellationToken cancellationToken)
        {
            AuthenticationResult   authResult = null;
            IEnumerable <IAccount> accounts   = await mClientApp.GetAccountsAsync().ConfigureAwait(false);

            IAccount firstAccount = accounts.FirstOrDefault();

            //AcquireTokenSilent pobiera token z pliku cache, i jesli jest tam zapisane jakies konto to je loguje a jak nie to looguje po raz pierwszy przez strone
            try
            {
                authResult = await mClientApp.AcquireTokenSilent(mScopes, firstAccount).ExecuteAsync(cancellationToken).ConfigureAwait(false);
            }
            catch (MsalUiRequiredException ex)
            {
                try
                {
                    authResult = await mClientApp.AcquireTokenInteractive(mScopes)
                                 .WithAccount(accounts.FirstOrDefault())
                                 .WithPrompt(Microsoft.Identity.Client.Prompt.SelectAccount)
                                 .ExecuteAsync(cancellationToken).ConfigureAwait(false);
                }
                catch (MsalException msalex)
                {
                    throw;
                    //TODO: zalogowac przypadek z msalex
                }
            }
            catch (MsalClientException ex)
            {
                throw;
                //TODO: zalogowac przypadek z msalex
            }

            // Tutaj TokenResponse przechowuje informacje o uzytkowniku z tokenu
            if (authResult != null)
            {
                string tokenResponse = await GetHttpContentWithToken(mGraphAPIEndpoint, authResult.AccessToken, cancellationToken).ConfigureAwait(false);

                MicrosoftAvatarDownloader microsoftAvatarDownloader = new MicrosoftAvatarDownloader(mClientApp, mScopes);
                mUser = new UserAccountFactory().Create(AuthenticationProvider.Microsoft, tokenResponse);
                await microsoftAvatarDownloader.GetAvatarAsync(cancellationToken).ConfigureAwait(false);
            }
        }
예제 #29
0
        public void CreateUser_OnNonExistingUser_ReturnsUserWithID()
        {
            // ARRANGE
            DbContextOptions <TestDatabaseContext> options = new DbContextOptionsBuilder <TestDatabaseContext>()
                                                             .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                                                             .Options;
            IDatabaseContext dbContext  = new TestDatabaseContext(options);
            UserRepository   repository = new UserRepository(dbContext);

            // ACT
            UserPublic userPublic = repository.CreateUser(new UserPublic {
                ID = 99, FirstName = "Jan", LastName = "Kowalski", OAuthID = "12345"
            });

            // ASSERT
            userPublic.Should().BeEquivalentTo(new UserPublic {
                ID = 1, FirstName = "Jan", LastName = "Kowalski", OAuthID = "12345"
            });
        }
예제 #30
0
        public async Task <ActionResult> SetUser(UserPublic user)
        {
            var info = await _userManager.FindByIdAsync(User.FindFirstValue(ClaimTypes.NameIdentifier));

            if (info.Id == user.Id)
            {
                await SetUserInfoFromUserPublic(user, info);
            }
            else if ((await _userManager.GetRolesAsync(info))[0] != "Admin")
            {
                return(NotFound());
            }
            var rawInfo = await _userManager.FindByIdAsync(user.Id.ToString());

            if (rawInfo == null)
            {
                return(NotFound());
            }
            await SetUserInfoFromUserPublic(user, rawInfo);

            return(Ok());
        }