Example #1
0
        public User HandleUserLogin(GoogleUserProfile user)
        {
            if (user == null)
            {
                return(null);
            }

            var existingUser = UserRepository.GetUserById(user.UserId);

            if (existingUser == null)
            {
                var newUser = new User
                {
                    UserId     = user.UserId,
                    Email      = user.Email,
                    FamilyName = user.FamilyName,
                    GivenName  = user.GivenName,
                    Name       = user.Name,
                    CreatedAt  = DateTime.UtcNow,
                    Role       = TimeTableRole.Student
                };
                UserRepository.CreateUser(newUser);
                return(newUser);
            }

            existingUser.LastLogin = DateTime.UtcNow;
            UserRepository.UpdateUser(existingUser);
            return(existingUser);
        }
Example #2
0
        public BookingAvailability BookRoom(Booking booking, GoogleUserProfile user)
        {
            var logger = LogManager.GetLogger("BookingService");

            logger.Info($"Executing Booking request for UserId {user.UserId}");

            var existingLessons = ClassroomRepository.GetCoursesByRoomAndWeek(booking.Classroom, booking.Week);
            var blockingLessons = CourseAvailability(existingLessons, booking);

            logger.Info($"Booking: There are {blockingLessons.Count} blocking lessons");
            if (blockingLessons.Count > 0)
            {
                logger.Info($"There was already a lesson planned during this time for this booking. {blockingLessons.Count}");
                return(Engine.Bookings.BookingAvailability.Scheduled);
            }

            var existingBookings = BookingRepository.GetBookingsByRoomAndWeek(booking.Classroom, booking.Week);
            var blockingBookings = BookingAvailability(existingBookings, booking);

            logger.Info($"Booking: There are {blockingBookings.Count} blocking bookings");

            if (blockingBookings.Count > 0)
            {
                logger.Info($"There was already a booking planned during this time for this booking. {blockingBookings.Count}");
                return(Engine.Bookings.BookingAvailability.Booked);
            }

            logger.Info($"No blocking lessons or bookings. Creating new booking");
            booking.Owner  = user.UserId;
            booking.Lokaal = ClassroomRepository.GetClassroomById(booking.Classroom);
            BookingRepository.CreateBooking(booking);
            logger.Info($"Booking success");
            return(Engine.Bookings.BookingAvailability.Success);
        }
Example #3
0
 public Athlete(GoogleUserProfile profile)
 {
     Name             = profile.Name;
     Email            = profile.Email;
     AuthenticationId = profile.Id;
     ProfileImageUrl  = profile.Picture;
     Initialize();
 }
    private void GetAuthInfo(string code)
    {
        GoogleAccessToken accessTokenInfo = GetAccessTokenInfo(code);

        GoogleUserProfile userInfo = GetUserInfo(accessTokenInfo.access_token);

        Response.Write(userInfo.given_name + " " + userInfo.family_name);
    }
Example #5
0
        public async Task <GoogleSSOResponse> LoginOrRegisterGoogleUser(GoogleTokenResponse googleTokenResponse, bool isAdmin)
        {
            GoogleUserProfile googleUser = await GoogleOAuthClient.GetUserProfile(googleTokenResponse.AccessToken);

            int userId = await FindExistingUserOrRegister(googleUser, isAdmin);

            string        budgeterClientId  = EnvironmentRequester.GetVariable("ServiceClientId");
            BudgeterToken authTokenResponse = await GetAuthTokenForUser(userId, budgeterClientId, "Google");

            return(new GoogleSSOResponse(googleTokenResponse, authTokenResponse));
        }
        public bool BasicAuth(string token, ILog logger)
        {
            var data          = Convert.FromBase64String(token);
            var decodedString = Encoding.UTF8.GetString(data);

            var dashboardRegex = Regex.Match(decodedString, "Dashboard:(.*):(.*):(.*):(.*):(.*)");

            if (dashboardRegex.Success)
            {
                var dashboardToken = WebConfigurationManager.AppSettings["BasicAuth.Dashboard.Token"];
                if (dashboardRegex.Groups[1].Value != dashboardToken)
                {
                    return(false);
                }
                if (!dashboardRegex.Groups[3].Value.EndsWith("@hr.nl"))
                {
                    return(false);
                }

                UserId      = dashboardRegex.Groups[2].Value;
                UserProfile = new GoogleUserProfile
                {
                    UserId     = UserId,
                    Email      = dashboardRegex.Groups[3].Value,
                    Name       = dashboardRegex.Groups[4].Value,
                    FamilyName = dashboardRegex.Groups[5].Value,
                    GivenName  = dashboardRegex.Groups[4].Value + " " + dashboardRegex.Groups[5].Value
                };
                return(true);
            }

            var piRegex = Regex.Match(decodedString, "(Pi)(:)(.*)"); //Pi:H.1.110

            if (piRegex.Success)
            {
                UserId      = piRegex.Groups[3].Value;
                UserProfile = new GoogleUserProfile
                {
                    UserId     = UserId,
                    Name       = "Pi",
                    FamilyName = piRegex.Groups[3].Value,
                    GivenName  = $"Pi {piRegex.Groups[3].Value}"
                };
                return(true);
            }

            return(false);
        }
        public async Task <ActionResult> OAuthCallback(string code)
        {
            GoogleOAuthParameters googleOAuthParameters = new GoogleOAuthParameters();

            HttpClient         client  = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://oauth2.googleapis.com/token");

            List <KeyValuePair <string, string> > formValues = new List <KeyValuePair <string, string> >();

            formValues.Add(new KeyValuePair <string, string>("code", code));
            formValues.Add(new KeyValuePair <string, string>("client_id", googleOAuthParameters.client_id));
            formValues.Add(new KeyValuePair <string, string>("client_secret", googleOAuthParameters.client_secret));
            formValues.Add(new KeyValuePair <string, string>("redirect_uri", googleOAuthParameters.redirect_uri));
            formValues.Add(new KeyValuePair <string, string>("grant_type", "authorization_code"));
            request.Content = new FormUrlEncodedContent(formValues);

            HttpResponseMessage response = await client.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                string responseBody = await response.Content.ReadAsStringAsync();

                GoogleTokenResponse token = JsonConvert.DeserializeObject <GoogleTokenResponse>(responseBody);

                HttpRequestMessage userProfileRequest = new HttpRequestMessage(HttpMethod.Get, "https://www.googleapis.com/oauth2/v2/userinfo");
                userProfileRequest.Headers.Add("Authorization", "Bearer " + token.access_token);
                HttpResponseMessage userProfileResponse = await client.SendAsync(userProfileRequest);

                if (userProfileResponse.IsSuccessStatusCode)
                {
                    string userProfileJson = await userProfileResponse.Content.ReadAsStringAsync();

                    GoogleUserProfile userProfile = JsonConvert.DeserializeObject <GoogleUserProfile>(userProfileJson);

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    return(RedirectToAction("Error", "Home"));
                }
            }
            else
            {
                return(RedirectToAction("Error", "Home"));
            }
        }
Example #8
0
        /// <summary>
        /// Attempts to get the user profile from Google. Will use the refresh token if the auth token has expired
        /// </summary>
        async public Task <bool> GetUserProfile()
        {
            //Can't get profile w/out a token
            if (RoomieApp.AuthToken == null)
            {
                return(false);
            }

            if (AuthUserProfile != null)
            {
                return(true);
            }

            using (new Busy(this))
            {
                AuthenticationStatus = "Getting Google user profile";
                var task = GoogleApiService.Instance.GetUserProfile();
                await RunSafe(task, false);

                if (task.IsFaulted && task.IsCompleted)
                {
                }

                if (task.IsCompleted && !task.IsFaulted && task.Result != null)
                {
                    AuthenticationStatus = "Authentication complete";
                    AuthUserProfile      = task.Result;

                    //InsightsManager.Identify(AuthUserProfile.Email, new Dictionary<string, string> {
                    //    {
                    //        "Name",
                    //        AuthUserProfile.Name
                    //    }
                    //});

                    Settings.Instance.AuthUserID = AuthUserProfile.Id;
                    await Settings.Instance.Save();
                }
                else
                {
                    AuthenticationStatus = "Unable to authenticate";
                }
            }

            return(AuthUserProfile != null);
        }
Example #9
0
        /// <summary>
        /// Registers an athlete with the backend and returns the new roomie profile
        /// </summary>
        async Task <Roomie> RegisterAthlete(GoogleUserProfile profile)
        {
            AuthenticationStatus = "Registering Roomie";
            var roomie = new Roomie(profile);

            var task = AzureService.Instance.SaveRoomie(roomie);

            await RunSafe(task);

            if (task.IsCompleted && task.IsFaulted)
            {
                return(null);
            }

            "You're now an registered as roomie!".ToToast();
            return(roomie);
        }
Example #10
0
        public void LogOut(bool clearCookies)
        {
            // Utility.SetSecured("AuthToken", string.Empty, "xamarin.sport", "authentication");
            AzureService.Instance.Client.Logout();

            RoomieApp.AuthToken          = null;
            AuthUserProfile              = null;
            Settings.Instance.RoomieID   = null;
            Settings.Instance.AuthUserID = null;

            if (clearCookies)
            {
                Settings.Instance.RegistrationComplete = false;
                _authenticator.ClearCookies();
            }

            Settings.Instance.Save();
        }
    GoogleUserProfile GetUserInfo(string access_token)
    {
        string getUserProfileUrl =
            string.Format("https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token={0}", access_token);
        //, access_token);
        //https://www.google.com/m8/feeds/contacts/default/full?access_token={0}", access_token);

        HttpWebRequest  request      = (HttpWebRequest)WebRequest.Create(getUserProfileUrl);
        HttpWebResponse response     = (HttpWebResponse)request.GetResponse();
        Encoding        enc          = Encoding.GetEncoding("utf-8");
        StreamReader    configStream = new StreamReader(response.GetResponseStream(), enc);
        string          profileJson  = configStream.ReadToEnd();

        JavaScriptSerializer serializer  = new JavaScriptSerializer();
        GoogleUserProfile    userProfile = serializer.Deserialize <GoogleUserProfile>(profileJson);

        return(userProfile);
    }
Example #12
0
        public async Task <int> RegisterGoogleUser(GoogleUserProfile googleUser, bool isAdmin)
        {
            // Register the new user
            RegistrationRequest registrationRequest = new RegistrationRequest
            {
                Username              = googleUser.Email,
                RegistrationChannel   = "Google-SSO-Provider",
                UserProfileProperties = new List <UserProfileProperty>
                {
                    new UserProfileProperty
                    {
                        ProfilePropertyName = "GoogleId",
                        Value = googleUser.Id
                    },
                    new UserProfileProperty
                    {
                        ProfilePropertyName = "FirstName",
                        Value = googleUser.GivenName
                    },
                    new UserProfileProperty
                    {
                        ProfilePropertyName = "LastName",
                        Value = googleUser.FamilyName
                    },
                    new UserProfileProperty
                    {
                        ProfilePropertyName = "Email",
                        Value = googleUser.Email
                    }
                }
            };

            RegistrationLogic registrationLogic = new RegistrationLogic(Cache, BudgeterLock, AuthContext, UserContext, SettingRequester, isAdmin);

            RegistrationRequest registrationResponse = await registrationLogic.RegisterUser(registrationRequest);

            return(registrationResponse.UserId);
        }
Example #13
0
        public async Task <int> FindExistingUserOrRegister(GoogleUserProfile googleUser, bool isAdmin)
        {
            //Search for user by GoogleId PP
            var searchLogic = new SearchLogic(Cache, UserContext);

            var search = new UserSearch
            {
                SearchText          = googleUser.Id,
                ProfilePropertyName = "GoogleId"
            };

            Page <UserSearchResponse> searchResponse = await searchLogic.Search(search);

            if (searchResponse != null && searchResponse.Records != null && searchResponse.Records.Count > 0)
            {
                return(searchResponse.Records.Select(x => x.UserId).FirstOrDefault());
            }
            else
            {
                //Search for user by Google Email as Username
                var usernameSearch = new UserSearch
                {
                    SearchText     = googleUser.Email,
                    SearchUsername = true
                };

                searchResponse = await searchLogic.Search(usernameSearch);
            }

            if (searchResponse != null && searchResponse.Records != null && searchResponse.Records.Count > 0)
            {
                UserSearchResponse user = searchResponse.Records.FirstOrDefault();
                await AddGoogleIdToProfileProperty(user, googleUser.Id, isAdmin);

                return(user.UserId);
            }
            else
            {
                //Search for user by Google Email as Email PP
                var emailSearch = new UserSearch
                {
                    SearchText          = googleUser.Email,
                    ProfilePropertyName = "Email"
                };

                searchResponse = await searchLogic.Search(emailSearch);
            }

            if (searchResponse != null && searchResponse.Records != null && searchResponse.Records.Count > 0)
            {
                UserSearchResponse user = searchResponse.Records.FirstOrDefault();
                await AddGoogleIdToProfileProperty(user, googleUser.Id, isAdmin);

                return(user.UserId);
            }
            else
            {
                //User does not exist, so Register them
                return(await RegisterGoogleUser(googleUser, isAdmin));
            }
        }
        public override async Task <HttpResponseMessage> ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)
        {
            var logger = LogManager.GetLogger("TimeTableApiController");

            try
            {
                var header = controllerContext.Request.Headers.Authorization;
                if (header == null)
                {
                    logger.Info($"Empty Authorization header.");
                    return(controllerContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "UnAuthorized"));
                }

                //Debug section
                var debugSetting = WebConfigurationManager.AppSettings["debug"];
                var debug        = bool.Parse(debugSetting);
                if (debug)
                {
                    if (header.Scheme == "tt2")
                    {
                        UserId      = "Kaj";
                        UserProfile = new GoogleUserProfile
                        {
                            UserId     = UserId,
                            Email      = "DEBUG",
                            Name       = "DEBUG",
                            FamilyName = "DEBUG",
                            GivenName  = "DEBUG"
                        };

                        logger.Info($"Logged in with Debug Authentication.");
                        return(await base.ExecuteAsync(controllerContext, cancellationToken));
                    }
                }

                //Non-debug Authorization
                bool auth;
                switch (header.Scheme)
                {
                case "Bearer":
                    auth = await GoogleAuth(header.Parameter, logger);

                    break;

                case "Basic":
                    auth = BasicAuth(header.Parameter, logger);
                    break;

                default:
                    return(controllerContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "UnAuthorized"));
                }

                if (auth)
                {
                    return(await base.ExecuteAsync(controllerContext, cancellationToken));
                }
                return(controllerContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "UnAuthorized"));
            }
            catch (Exception e)
            {
                logger.Error($"An error occured", e);
                //var message = string.Format("error occured in {0} : {1}", controllerContext.Request.RequestUri, e.Message);
                return(controllerContext.Request.CreateResponse(HttpStatusCode.InternalServerError, "InternalServerError"));
            }
        }
		public void LogOut(bool clearCookies)
		{
			Utility.SetSecured("AuthToken", string.Empty, "xamarin.sport", "authentication");
			AzureService.Instance.Client.Logout();

			App.AuthToken = null;
			AuthUserProfile = null;
			Settings.Instance.AthleteId = null;
			Settings.Instance.AuthUserID = null;

			if(clearCookies)
			{
				Settings.Instance.RegistrationComplete = false;
				_authenticator.ClearCookies();
			}

			Settings.Instance.Save();
		}
		/// <summary>
		/// Attempts to get the user profile from Google. Will use the refresh token if the auth token has expired
		/// </summary>
		async public Task<bool> GetUserProfile()
		{
			//Can't get profile w/out a token
			if(App.AuthToken == null)
				return false;

			if(AuthUserProfile != null)
				return true;

			using(new Busy(this))
			{
				AuthenticationStatus = "Getting Google user profile";
				var task = GoogleApiService.Instance.GetUserProfile();
				await RunSafe(task, false);

				if(task.IsFaulted && task.IsCompleted)
				{
					//Need to get refresh token from Azure somehow
					//Likely our authtoken has expired
//					AuthenticationStatus = "Refreshing token";
//
//					var refreshTask = GoogleApiService.Instance.GetNewAuthToken(Settings.Instance.RefreshToken);
//					await RunSafe(refreshTask);
//
//					if(refreshTask.IsCompleted && !refreshTask.IsFaulted)
//					{
//						//Success in getting a new auth token - now lets attempt to get the profile again
//						if(!string.IsNullOrWhiteSpace(refreshTask.Result) && App.AuthToken != refreshTask.Result)
//						{
//							//We have a valid token now, let's try this again
//							App.AuthToken = refreshTask.Result;
//							await Settings.Instance.Save();
//							return await GetUserProfile();
//						}
//					}
				}

				if(task.IsCompleted && !task.IsFaulted && task.Result != null)
				{
					AuthenticationStatus = "Authentication complete";
					AuthUserProfile = task.Result;

					InsightsManager.Identify(AuthUserProfile.Email, new Dictionary<string, string> {
						{
							"Name",
							AuthUserProfile.Name
						}
					});

					Settings.Instance.AuthUserID = AuthUserProfile.Id;
					await Settings.Instance.Save();
				}
				else
				{
					AuthenticationStatus = "Unable to authenticate";
				}
			}

			return AuthUserProfile != null;
		}
		/// <summary>
		/// Registers an athlete with the backend and returns the new athlete profile
		/// </summary>
		async Task<Athlete> RegisterAthlete(GoogleUserProfile profile)
		{
			AuthenticationStatus = "Registering athlete";
			var athlete = new Athlete(profile);

			var task = AzureService.Instance.SaveAthlete(athlete);
			await RunSafe(task);

			if(task.IsCompleted && task.IsFaulted)
				return null;

			"You're now an officially registered athlete!".ToToast();
			return athlete;
		}