public ActionResult Login(LoginViewModel model, string returnUrl)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(View(model));
                }

                CEUserManager    ceUserManager         = new CEUserManager();
                SHA1HashProvider sHA1HashProvider      = new SHA1HashProvider();
                User             anActiveOrBlockedUser = ceUserManager.GetSigningUserByEmail(model.Email);

                if (anActiveOrBlockedUser != null && sHA1HashProvider.CheckHashSHA1(model.Password, anActiveOrBlockedUser.Password, 8))
                {
                    UserDTO userDTO = EntityDTOHelper.GetEntityDTO <User, UserDTO>(anActiveOrBlockedUser);
                    AuthenticatedUserInfo authenticatedUserInfo = new AuthenticatedUserInfo(userDTO);

                    ceUserManager.SignInUser(HttpContext, string.Format("{0}", authenticatedUserInfo.FullName), false);

                    Session["loggeduser"] = authenticatedUserInfo;

                    SessionManager.RegisterSessionActivity(loggedInAt: DateTime.Now);

                    return(this.RedirectToLocal(returnUrl));
                }

                ModelState.AddModelError(string.Empty, "Login attempt failed.");
            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.WriteLine(e);
            }
            return(this.View(model));
        }
        /// <summary>Get a full email address, if not already provided.</summary>
        protected string GetFullEmailAddress(string account, AuthenticatedUserInfo authInfo)
        {
            if (string.IsNullOrWhiteSpace(account))
            {
                return(null);
            }

            //assume an address already containing the @ symbol is already a full email address
            if (account.Contains("@"))
            {
                return(account);
            }
            else
            {
                var domain = string.Empty;

                //we don't have a domain. first try the originally provided domain
                if (!string.IsNullOrWhiteSpace(authInfo.originalDomain))
                {
                    domain = authInfo.originalDomain;
                }
                else if (!string.IsNullOrWhiteSpace(authInfo.domain))
                {
                    domain = authInfo.domain;
                }
                else
                {
                    domain = OAuth2Base.CheckDomain();
                }

                //will return null if acct or domain is blank
                return(Utils.GetFullEmailAddress(account, domain));
            }
        }
示例#3
0
 private static void CheckUserInfoValues(AuthenticatedUserInfo info, int id, string email, string data)
 {
     Assert.IsNotNull(info);
     Assert.AreEqual(email, info.Email);
     Assert.AreEqual(id, info.Id);
     Assert.AreEqual(data, info.Data);
 }
示例#4
0
        public ActionResult EditDinerProfile(string identifier)
        {
            if (Session != null && Session.Contents != null)
            {
                AuthenticatedUserInfo authenticatedUserInfo = Session["loggeduser"] as AuthenticatedUserInfo;

                if (authenticatedUserInfo != null)
                {
                    UserDTO userDTO = EntityDTOHelper.GetEntityDTO <DAL.User, UserDTO>(new CEUserManager().FindById(
                                                                                           int.Parse(DataSecurityTripleDES.GetPlainText(authenticatedUserInfo.UserId))));

                    CraveatsDinerViewModel craveatsDinerViewModel = null;

                    if (((Common.UserTypeEnum)userDTO.UserTypeFlag).HasFlag(Common.UserTypeEnum.CraveatsDiner))
                    {
                        craveatsDinerViewModel = new CraveatsDinerViewModel()
                        {
                            Id            = userDTO.Id,
                            ContactNumber = userDTO.ContactNumber,
                            Email         = userDTO.EmailAddress,
                            FirstName     = userDTO.FirstName,
                            Surname       = userDTO.Surname,
                            Role          = Common.UserTypeEnum.CraveatsDiner.GetDescription()
                        };
                    }
                    return(View("EditDinerProfile", craveatsDinerViewModel));
                }
            }
            return(View("Error"));
        }
示例#5
0
        public static bool RegisterSessionActivity(int?userID = null, DateTime?loggedInAt = null, DateTime?loggedOffAt = null)
        {
            object xLock = new object();

            lock (xLock) {
                AuthenticatedUserInfo authenticatedUserInfo = HttpContext.Current.Session["loggeduser"] as AuthenticatedUserInfo;
                if (EditSessionTracking(new SessionTracking()
                {
                    SessionID = HttpContext.Current.Session.SessionID,
                    IPAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? string.Empty).Trim() == string.Empty
                    ? HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]?.Trim()
                    : HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]?.Trim(),
                    UserId = userID.HasValue ? userID : authenticatedUserInfo != null
                        ? (int?)int.Parse(DataSecurityTripleDES.GetPlainText(authenticatedUserInfo.UserId))
                        : null,
                    LoggedInAt = loggedInAt,
                    LoggedOutAt = loggedOffAt
                }) != null)
                {
                    return(true);
                }
                ;
                return(false);
            }
        }
        public async Task <ActionResult> ChangePassword(ChangePasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            loggedUserId = int.Parse(DataSecurityTripleDES.GetPlainText(model.UserId));
            var result = await ceUserManager.ChangePasswordAsync(loggedUserId, model.OldPassword, model.NewPassword);

            if (result.Succeeded)
            {
                var userDTO = await ceUserManager.FindByIdAsync(loggedUserId);

                if (userDTO != null)
                {
                    AuthenticatedUserInfo authenticatedUserInfo = new AuthenticatedUserInfo(userDTO);

                    Session["loggeduser"] = authenticatedUserInfo;

                    SessionManager.RegisterSessionActivity(userID: loggedUserId, loggedInAt: DateTime.Now);

                    await ceUserManager.SignIn(username : authenticatedUserInfo.FullName, isPersistent : false, rememberBrowser : false);
                }
                return(RedirectToAction("Index", new { Message = ManageMessageId.ChangePasswordSuccess }));
            }
            AddErrors(result);
            return(View(model));
        }
 public ManageController()
 {
     if (Session != null && Session.Contents != null && Session["loggeduser"] != null)
     {
         AuthenticatedUserInfo authenticatedUserInfo = Session["loggeduser"] as AuthenticatedUserInfo;
         loggedUserId = int.Parse(DataSecurityTripleDES.GetPlainText(authenticatedUserInfo.UserId));
     }
 }
示例#8
0
        public ActionResult PartnerRestaurant(PartnerRestaurantViewModel model)
        {
            if (Session != null && Session.Contents != null)
            {
                AuthenticatedUserInfo authenticatedUserInfo = Session["loggeduser"] as AuthenticatedUserInfo;

                if (authenticatedUserInfo != null)
                {
                    UserDTO userDTO = EntityDTOHelper.GetEntityDTO <DAL.User, UserDTO>(new CEUserManager().FindById(
                                                                                           int.Parse(DataSecurityTripleDES.GetPlainText(authenticatedUserInfo.UserId))));

                    PartnerRestaurantViewModel partnerRestaurantViewModel = null;

                    if (((Common.UserTypeEnum)userDTO.UserTypeFlag).HasFlag(Common.UserTypeEnum.PartnerRestaurant))
                    {
                        partnerRestaurantViewModel = new PartnerRestaurantViewModel()
                        {
                            Id            = userDTO.Id,
                            ContactNumber = userDTO.ContactNumber,
                            Email         = userDTO.EmailAddress,
                            FirstName     = userDTO.FirstName,
                            Surname       = userDTO.Surname,
                            Role          = Common.UserTypeEnum.PartnerRestaurant.GetDescription()
                        };
                    }

                    if ((userDTO.AddressId ?? "").Length > 0)
                    {
                        DataProvider dataProvider = new DataProvider();

                        DAL.Address anAddress = dataProvider.FindAddressById(
                            int.Parse(DataSecurityTripleDES.GetPlainText(userDTO.AddressId)));

                        AddressViewModel addressViewModel = EntityDTOHelper.GetEntityDTO <DAL.Address, AddressViewModel>(anAddress);

                        if (anAddress != null)
                        {
                            DAL.Region region = dataProvider.FindRegionById(anAddress.RegionId ?? 0);

                            if (region != null)
                            {
                                addressViewModel.RegionAlias = region.RegionAlias;
                                addressViewModel.RegionId    = DataSecurityTripleDES.GetEncryptedText(region.Id);
                            }

                            partnerRestaurantViewModel.Addresses = new List <AddressViewModel>()
                            {
                                addressViewModel
                            };
                        }
                    }

                    return(View("PartnerRestaurant", partnerRestaurantViewModel));
                }
            }

            return(View("Error"));
        }
示例#9
0
        internal static UserTypeEnum GetContextSessionOwnerType()
        {
            object xLock = new object();

            lock (xLock) {
                AuthenticatedUserInfo authenticatedUserInfo =
                    HttpContext.Current.Session["loggeduser"] as AuthenticatedUserInfo;
                return((UserTypeEnum)authenticatedUserInfo.UserRoleEnum);
            }
        }
示例#10
0
        public static string GetContextSessionLoggedUserEmailAddress()
        {
            object xLock = new object();

            lock (xLock)
            {
                AuthenticatedUserInfo authenticatedUserInfo =
                    HttpContext.Current.Session["loggeduser"] as AuthenticatedUserInfo;
                return(authenticatedUserInfo?.EmailAddress);
            }
        }
示例#11
0
        internal static string GetContextSessionLoggedUserID()
        {
            object xLock = new object();

            lock (xLock)
            {
                AuthenticatedUserInfo authenticatedUserInfo =
                    HttpContext.Current.Session["loggeduser"] as AuthenticatedUserInfo;
                return(authenticatedUserInfo?.UserId);
            }
        }
        //
        // GET: /Manage/ChangePassword
        public ActionResult ChangePassword()
        {
            var model = new ChangePasswordViewModel();

            if (Session["loggeduser"] != null)
            {
                AuthenticatedUserInfo authenticatedUserInfo = Session["loggeduser"] as AuthenticatedUserInfo;
                model.UserId = authenticatedUserInfo.UserId;
            }
            return(View(model));
        }
        public bool UserInFunction(string function)
        {
            AuthenticatedUserInfo userInfo = _authenticationService.GetCurrentUser();

            if (userInfo == null)
            {
                return(false);
            }
            IEnumerable <string> functions = ListFunctionsForRoles(userInfo.User.Roles);

            return(functions.Where(f => f == function).Count() > 0);
        }
示例#14
0
 /*
  * Получает токен
  */
 private ISessionToken GetSessionToken(string code, string signature)
 {
     try
     {
         var authenticatedUserInfo = new AuthenticatedUserInfo(code, signature, null);
         return(Client.GetSessionToken(authenticatedUserInfo).Result);
     }
     catch (AggregateException ex)
     {
         Log.WriteError(ex.InnerException);
         return(null);
     }
 }
示例#15
0
        /// <summary>
        /// Build the service and return the domain the service is working on.
        /// </summary>
        public AuthenticatedUserInfo BuildService(AuthenticatedUserInfo authInfo, string serviceAccountUser = null)
        {
            if (authInfo == null) {return null;}

            if (string.IsNullOrWhiteSpace(serviceAccountUser))
            {
                if (!services.ContainsKey(authInfo))
                {
                    //this sets the OAuth2Base current domain and default domain, if necessary
                    T service = CreateNewService(OAuth2Base.GetAppName(apiNameAndVersion), authInfo);

                    //current domain should be set at this point 
                    if (authInfo.domain == "gmail.com" && !worksWithGmail)
                    {
                        throw new Exception("This Google API is not available for a Gmail account.");
                    }
                    else
                    {
                        services.Add(authInfo, service);
                    }
                }
            }
            else
            {
                if (!serviceAccountServices.ContainsKey(authInfo))
                {
                    serviceAccountServices.Add(authInfo, new Dictionary<string,T>());
                }

                if (!serviceAccountServices[authInfo].ContainsKey(serviceAccountUser))
                {
                    T service = CreateNewService(OAuth2Base.GetAppName(apiNameAndVersion), authInfo, serviceAccountUser);

                    if (authInfo.domain == "gmail.com" && !worksWithGmail)
                    {
                        throw new Exception("This Google API is not available for a Gmail account.");
                    }
                    else
                    {
                        serviceAccountServices[authInfo].Add(serviceAccountUser, service);
                    }
                }
            }

            return authInfo;
        }
示例#16
0
        public AuthenticatedUserInfo ChooseScopesAndAuthenticate(string api, string version, ClientSecrets secrets)
        {
            var info = new AuthenticatedUserInfo()
            {
                apiNameAndVersion = api + ":" + version,
                scopes            = ChooseScopes(api, version)
            };

            string script = "Read-Host '\nYou will now authenticate for this API. Press any key to continue'";
            Collection <PSObject> results = invokablePSInstance.InvokeCommand.InvokeScript(script);

            //Now, authenticate.
            info = OAuth2Base.GetAuthTokenFlow(info, secrets, force: true);

            PrintPretty(string.Format("{0}:{1} has been authenticated and saved.", api, version), "green");

            return(info);
        }
示例#17
0
        /// <summary>
        /// Returns the loaded and authenticated service for this domain. Returns null if it doesn't exist.
        /// </summary>
        public static T GetService(AuthenticatedUserInfo AuthInfo, string serviceAccountUser = null)
        {
            if (string.IsNullOrWhiteSpace(serviceAccountUser))
            {
                if (services.ContainsKey(AuthInfo))
                {
                    return services[AuthInfo];
                }
            }
            else
            {
                if (serviceAccountServices.ContainsKey(AuthInfo)
                    && serviceAccountServices[AuthInfo].ContainsKey(serviceAccountUser))
                {
                    return serviceAccountServices[AuthInfo][serviceAccountUser];
                }
            }

            return default(T);
        }
示例#18
0
        public ActionResult ProfileView(ProfileViewModel model)
        {
            model = new ProfileViewModel();

            if (Session != null && Session.Contents != null)
            {
                AuthenticatedUserInfo authenticatedUserInfo = Session["loggeduser"] as AuthenticatedUserInfo;

                if (authenticatedUserInfo != null)
                {
                    UserDTO userDTO = EntityDTOHelper.GetEntityDTO <DAL.User, UserDTO>(new CEUserManager().FindById(
                                                                                           int.Parse(DataSecurityTripleDES.GetPlainText(authenticatedUserInfo.UserId))));

                    model.ModelUserType = (Common.UserTypeEnum)userDTO.UserTypeFlag;

                    return(View(model));
                }
            }

            ModelState.AddModelError(string.Empty, "Session has expired");
            return(View("ProfileView", null));
        }
示例#19
0
        public AuthenticatedUserInfo AuthenticatePreChosenScopes(string api, string version, ClientSecrets secrets,
                                                                 ScopeSelectionTypes PreSelectScopes = ScopeSelectionTypes.None)
        {
            if (PreSelectScopes == ScopeSelectionTypes.None)
            {
                return(ChooseScopesAndAuthenticate(api, version, secrets));
            }
            else
            {
                Data.RestDescription restDescription = apis.RestData(api, version);

                HashSet <string> scopes = new HashSet <string>();

                switch (PreSelectScopes)
                {
                case ScopeSelectionTypes.ReadOnly:
                    scopes.UnionWith(restDescription.Auth.Oauth2.Scopes.Keys.Where(x => x.Contains("readonly")));
                    break;

                case ScopeSelectionTypes.ReadWrite:
                    scopes.UnionWith(restDescription.Auth.Oauth2.Scopes.Keys.Where(x => !x.Contains("readonly")));
                    break;

                default:
                    scopes.UnionWith(restDescription.Auth.Oauth2.Scopes.Keys);
                    break;
                }

                var authUserInfo = new AuthenticatedUserInfo()
                {
                    apiNameAndVersion = api + ":" + version,
                    scopes            = CheckForRequiredScope(scopes)
                };

                AuthenticatedUserInfo info = OAuth2Base.GetAuthTokenFlow(authUserInfo, secrets, force: true);

                return(info);
            }
        }
示例#20
0
        public ActionResult AddAddress(string ownerType = null, string ownerId = null)
        {
            if ((ownerType ?? string.Empty).Length > 0 && (ownerId ?? string.Empty).Length > 0)
            {
                ViewBag.AlterButtonTitle  = true;
                ViewBag.AlteredButtonName = "Next";
            }

            SessionManager.RegisterSessionActivity();

            if (Session != null && Session.Contents != null)
            {
                AuthenticatedUserInfo authenticatedUserInfo = Session["loggeduser"] as AuthenticatedUserInfo;

                if (authenticatedUserInfo != null)
                {
                    UserDTO userDTO = EntityDTOHelper.GetEntityDTO <DAL.User, UserDTO>(new CEUserManager().FindById(
                                                                                           int.Parse(DataSecurityTripleDES.GetPlainText(authenticatedUserInfo.UserId))));

                    if (((Common.UserTypeEnum)userDTO.UserTypeFlag).HasFlag(Common.UserTypeEnum.CraveatsDiner) ||
                        ((Common.UserTypeEnum)userDTO.UserTypeFlag).HasFlag(Common.UserTypeEnum.PartnerRestaurant))
                    {
                        IEnumerable <string> regionAliases = GetAllRegionAliases();

                        AddressViewModel addressViewModel = new AddressViewModel()
                        {
                            RegionAliases = GenUtil.GetSelectListItems(regionAliases),
                            OwnerId       = ownerId,
                            OwnerType     = ownerType
                        };

                        return(View("AddAddress", addressViewModel));
                    }
                }
            }
            return(View("Error"));
        }
示例#21
0
 protected override sharedcontacts_v3.SharedcontactsService CreateNewService(string domain, AuthenticatedUserInfo authInfo, string gShellServiceAccount = null)
 {
     return(new sharedcontacts_v3.SharedcontactsService(OAuth2Base.GetGdataInitializer(domain, authInfo)));
 }
 protected override emailsettings_v1.EmailsettingsService CreateNewService(string domain, AuthenticatedUserInfo authInfo, string gShellServiceAccount = null)
 {
     return(new emailsettings_v1.EmailsettingsService(OAuth2Base.GetGdataInitializer(domain, authInfo)));
 }
示例#23
0
 /// <summary>
 /// A method specific to each inherited object, called during authentication. Must be implemented.
 /// </summary>
 protected override AuthenticatedUserInfo Authenticate(AuthenticatedUserInfo AuthUserInfo, ClientSecrets Secrets)
 {
     return(null);
 }
示例#24
0
 /// <summary>
 /// Initialize and return a new DiscoveryService
 /// </summary>
 protected override discovery_v1.DiscoveryService CreateNewService(string domain, AuthenticatedUserInfo authInfo, string serviceAcctUser)
 {
     return(new discovery_v1.DiscoveryService(OAuth2Base.GetInitializer()));
 }
示例#25
0
        public void ParseValidTokenWithNoExtraDataWithTrailingSeparator()
        {
            AuthenticatedUserInfo info = AuthenticationToken.Parse("[email protected];3421;");

            CheckUserInfoValues(info, 3421, "*****@*****.**", string.Empty);
        }
 /// <summary>Load token and scope information for API call, and authenticate if necessary.</summary>
 protected abstract AuthenticatedUserInfo Authenticate(AuthenticatedUserInfo authUserInfo, ClientSecrets Secrets);
        public ActionResult Register(RegisterViewModel model)
        {
            SessionManager.RegisterSessionActivity();

            // Get all states again
            var roles = GetAllRoles();

            // Set these states on the model. We need to do this because
            // only the selected value from the DropDownList is posted back, not the whole
            // list of states.
            model.Roles = GenUtil.GetSelectListItems(roles);

            // In case everything is fine - i.e. both "Name" and "State" are entered/selected,
            // redirect user to the "Done" page, and pass the user object along via Session
            if (ModelState.IsValid)
            {
                SHA1HashProvider sHA1HashProvider = new SHA1HashProvider();
                if (!ceUserManager.IsRegistered(model.Email))
                {
                    string sha1HashText = sHA1HashProvider.SecureSHA1(model.Password.Trim());
                    int?   newUserID    = ceUserManager.RegisterNew(model.Email, sha1HashText, model.Role);
                    if (newUserID.HasValue)
                    {
                        UserDTO userDTO = new UserDTO()
                        {
                            Id         = DataSecurityTripleDES.GetEncryptedText(newUserID),
                            FirstName  = model.FirstName,
                            Surname    = model.Surname,
                            UserStatus = (int?)UserStatusEnum.Active
                        };

                        ceUserManager.SaveUserDetail(userDTO);

                        StringBuilder sbSubject   = new StringBuilder("Craveats new registrant notification"),
                                      sbEmailBody = new StringBuilder("<p>A new user with the following detail has been registered in the system. " +
                                                                      $"<br/><em>FirstName            </em>: {model.FirstName}" +
                                                                      $"<br/><em>Surname              </em>: {model.Surname}" +
                                                                      $"<br/><em>Email                </em>: {model.Email}" +
                                                                      $"<br/><em>Registration Type    </em>: {model.Role}" +
                                                                      "</p><p>Thank you.</p><p>Craveats</p>");

                        CommunicationServiceProvider.SendOutgoingNotification(
                            new MailAddress(
                                model.Email,
                                string.Format("{0}{1}{2}", model.FirstName, " ", model?.Surname).Trim()),
                            sbSubject.ToString(),
                            sbEmailBody.ToString());

                        User result = ceUserManager.FindByCriteria(email: model.Email, userStatusEnums: new List <int> {
                            (int)UserStatusEnum.Active, (int)UserStatusEnum.Blocked
                        });
                        if (result != null)
                        {
                            userDTO = EntityDTOHelper.GetEntityDTO <User, UserDTO>(result);

                            AuthenticatedUserInfo authenticatedUserInfo = new AuthenticatedUserInfo(userDTO);
                            Session["loggeduser"] = authenticatedUserInfo;

                            SessionManager.RegisterSessionActivity(userID: result.Id, loggedInAt: DateTime.Now);

                            ceUserManager.SignInUser(HttpContext, string.Format("{0}", authenticatedUserInfo.FullName), false);

                            return(RedirectToAction("Index", "Home"));
                        }
                        else
                        {
                            ModelState.AddModelError(string.Empty, "An error occurred in reading user data. Please review input and re-try.");
                        }
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, "An error occurred in registering new user. Please review input and re-try.");
                    }
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Email is registered and cannot be used to create another account.");
                }
            }

            // Something is not right - so render the registration page again,
            // keeping the data user has entered by supplying the model.
            return(View("Register", model));
        }
        /// <summary>Determines if the user needs to be prompted to select the scopes.</summary>
        /// <remarks>
        /// Api is derived from the class that inherits this. User is the domain's default user. Returns null if scopes
        /// already exist since they'll be pulled up during authentication anyways.
        /// </remarks>
        public AuthenticatedUserInfo EnsureScopesExist(string GAuthId, HashSet <string> forcedScopes = null)
        {
            var results = new AuthenticatedUserInfo();

            string domain = null;
            string user   = null;

            bool gauthProvided = false;

            if (!string.IsNullOrWhiteSpace(GAuthId))
            {
                gauthProvided = true;

                if (GAuthId.Contains("@")) //user probably specified a full email address
                {
                    string gauthUser = GetUserFromEmail(GAuthId);
                    results.originalUser = gauthUser;

                    string gauthDomain = GetDomainFromEmail(GAuthId);
                    results.originalDomain = gauthDomain;

                    if (OAuth2Base.infoConsumer.DomainExists(gauthDomain))
                    {
                        domain = gauthDomain;

                        if (OAuth2Base.infoConsumer.UserExists(gauthDomain, gauthUser))
                        {
                            user = gauthUser; //else leave null - make them auth for that user since they specified it
                        }
                    }
                }
                else //either just a domain, or a user
                {
                    //check if it is a domain
                    if (OAuth2Base.infoConsumer.DomainExists(GAuthId))
                    {
                        domain = GAuthId;
                        results.originalDomain = GAuthId;
                        user = OAuth2Base.infoConsumer.GetDefaultUser(GAuthId); //could be null
                    }
                    else //not a domain that is saved
                    {
                        //try the default domain's users first, as a matter of best practice
                        string defaultDomain = OAuth2Base.infoConsumer.GetDefaultDomain();

                        if (!string.IsNullOrWhiteSpace(defaultDomain))
                        {
                            var users = OAuth2Base.infoConsumer.GetAllUsers(defaultDomain);

                            if (users.Select(x => x.userName).Contains(GAuthId))
                            {
                                domain = defaultDomain;
                                user   = GAuthId;
                                results.originalUser = GAuthId;
                            }
                            else //check other domains, if any
                            {
                                var domains = OAuth2Base.infoConsumer.GetAllDomains();

                                foreach (var domainObj in domains)
                                {
                                    users = OAuth2Base.infoConsumer.GetAllUsers(domainObj.domain);

                                    if (users.Select(x => x.userName).Contains(GAuthId))
                                    {
                                        domain = domainObj.domain;
                                        user   = GAuthId;
                                        results.originalUser = GAuthId;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            //****************//

            if (string.IsNullOrWhiteSpace(domain) && !gauthProvided)
            {
                //If the domain or user are missing, see if we can fill it in using the defaults
                domain = OAuth2Base.CheckDomain(domain);
                if (domain != null)
                {
                    user = OAuth2Base.CheckUser(domain, user);
                }
            }

            //now find out if that domain has a parent domain if we don't have a user provided even by default
            if (!string.IsNullOrWhiteSpace(domain) && string.IsNullOrWhiteSpace(user) &&
                !string.IsNullOrWhiteSpace(OAuth2Base.infoConsumer.GetDomain(domain).parentDomain))
            {
                var domainParent = OAuth2Base.infoConsumer.GetDomainMainParent(domain);
                if (domainParent != domain)
                {
                    domain = domainParent;
                    user   = OAuth2Base.infoConsumer.GetDefaultUser(domain);
                }
            }

            //****************//

            results.userName = user;
            results.domain   = domain;

            //if no domain is returned, none was provided or none was found as default.
            if (string.IsNullOrWhiteSpace(domain) || string.IsNullOrWhiteSpace(user) ||
                !OAuth2Base.infoConsumer.TokenAndScopesExist(domain, user, apiNameAndVersion))
            {
                string domainText = null;

                if (!string.IsNullOrWhiteSpace(domain))
                {
                    domainText = "is for domain (" + domain + "), which ";
                }

                WriteWarning(string.Format("The Cmdlet you've just started {0}doesn't"
                                           + " seem to have any saved authentication for this API ({1}). In order to continue you'll need to"
                                           + " choose which permissions gShell can use for this API.", domainText, apiNameAndVersion));

                string chooseApiNowScript = "Read-Host '\nWould you like to choose your API scopes now? y or n'";
                Collection <PSObject> chooseApiNowResults = this.InvokeCommand.InvokeScript(chooseApiNowScript);
                string result = chooseApiNowResults[0].ToString().Substring(0, 1).ToLower();
                if (result == "y")
                {
                    ScopeHandlerBase scopeBase = new ScopeHandlerBase(this);

                    results.scopes = scopeBase.ChooseScopes(
                        apiNameAndVersion.Split(':')[0],
                        apiNameAndVersion.Split(':')[1],
                        forcedScopes);

                    if (!string.IsNullOrWhiteSpace(GAuthId))
                    {
                        results.domain         = GetDomainFromEmail(GAuthId);
                        results.originalDomain = results.domain;
                    }

                    return(results);
                }
                else
                {
                    WriteWarning("No scopes were chosen. You can run this process manually with Invoke-ScopeManager later.");
                }
            }
            else
            {
                results.scopes = OAuth2Base.infoConsumer.GetTokenInfo(domain, user, apiNameAndVersion).scopes;
                return(results);
            }

            return(results);
        }
        /// <summary>Creates a new v1.GroupsMigration service.</summary>
        /// <param name="domain">The domain to which this service will be authenticated.</param>
        /// <param name="authInfo">The authenticated AuthInfo for this user and domain.</param>
        /// <param name="gShellServiceAccount">The optional email address the service account should impersonate.</param>

        protected override v1.GroupsMigrationService CreateNewService(string domain, AuthenticatedUserInfo authInfo, string gShellServiceAccount = null)
        {
            return(new v1.GroupsMigrationService(OAuth2Base.GetInitializer(domain, authInfo)));
        }
        /// <summary>Ensure the user, domain and client secret combination work with an authenticated user.</summary>
        /// <param name="Scopes">The scopes that need to be passed through to the user authentication to Google.</param>
        /// <param name="Secrets">The client secrets.`</param>
        /// <param name="Domain">The domain for which this authentication is intended.</param>
        /// <returns>The AuthenticatedUserInfo for the authenticated user.</returns>
        protected override AuthenticatedUserInfo Authenticate(AuthenticatedUserInfo authUserInfo, ClientSecrets Secrets)
        {
            authUserInfo.apiNameAndVersion = apiNameAndVersion;

            return(ServiceWrapperDictionary[mainBaseType].Authenticate(authUserInfo, Secrets));
        }