Exemplo n.º 1
0
        /// <summary>
        /// Get the current user.
        /// </summary>
        /// <param name="request">Request.</param>
        /// <returns>the current user</returns>
        public object Get(UserGetCurrentRequestTep request)
        {
            WebUserTep result;
            var        context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            try {
                context.Open();
                context.LogInfo(this, string.Format("/user/current GET"));
                UserTep user = UserTep.FromId(context, context.UserId);
                try {
                    user.PrivateSanityCheck();//we do it here, because we do not want to do on each Load(), and we are sure users always pass by here
                }catch (Exception e) {
                    context.LogError(this, e.Message, e);
                }
                result = new WebUserTep(context, user, false);
                try{
                    var cookie = DBCookie.LoadDBCookie(context, context.GetConfigValue("cookieID-token-access"));
                    result.Token = cookie.Value;
                    TimeSpan span = cookie.Expire.Subtract(DateTime.UtcNow);
                    result.TokenExpire = span.TotalSeconds;
                }catch (Exception) {}
                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(result);
        }
        public void CheckRefresh()
        {
            var      tokenaccess = DBCookie.LoadDBCookie(context, context.GetConfigValue("cookieID-token-access"));
            TimeSpan span        = tokenaccess.Expire.Subtract(DateTime.UtcNow);

            if (span.TotalMinutes < context.GetConfigIntegerValue("AccessTokenExpireMinutes"))
            {
                if (span.TotalMinutes < 0)
                {
                    throw new Exception("Token is not valid anymore");
                }
                else
                {
                    var tokenrefresh  = DBCookie.LoadDBCookie(context, context.GetConfigValue("cookieID-token-refresh"));
                    var tokenresponse = client.RefreshToken(tokenrefresh.Value);
                    DBCookie.StoreDBCookie(context, context.GetConfigValue("cookieID-token-access"), tokenresponse.access_token, context.Username, tokenresponse.expires_in);
                    DBCookie.StoreDBCookie(context, context.GetConfigValue("cookieID-token-refresh"), tokenresponse.refresh_token, context.Username);
                    if (!string.IsNullOrEmpty(tokenresponse.id_token))
                    {
                        DBCookie.StoreDBCookie(context, context.GetConfigValue("cookieID-token-id"), tokenresponse.id_token, context.Username, tokenresponse.expires_in);
                    }
                }
            }
        }
        public override User GetUserProfile(IfyWebContext context, HttpRequest request = null, bool strict = false)
        {
            NewUserCreated = false;

            UserTep            usr      = null;
            AuthenticationType authType = IfyWebContext.GetAuthenticationType(typeof(TepLdapAuthenticationType));

            var tokenrefresh = DBCookie.LoadDBCookie(context, context.GetConfigValue("cookieID-token-refresh"));
            var tokenaccess  = DBCookie.LoadDBCookie(context, context.GetConfigValue("cookieID-token-access"));

            context.LogDebug(this, string.Format("GetUserProfile -- tokenrefresh = {0} ; tokenaccess = {1}", tokenrefresh.Value, tokenaccess.Value));

            if (!string.IsNullOrEmpty(tokenrefresh.Value) && DateTime.UtcNow > tokenaccess.Expire)
            {
                // refresh the token
                try {
                    var tokenresponse = client.RefreshToken(tokenrefresh.Value);
                    DBCookie.StoreDBCookie(context, context.GetConfigValue("cookieID-token-access"), tokenresponse.access_token, tokenaccess.Username, tokenresponse.expires_in);
                    DBCookie.StoreDBCookie(context, context.GetConfigValue("cookieID-token-refresh"), tokenresponse.refresh_token, tokenrefresh.Username);
                    DBCookie.StoreDBCookie(context, context.GetConfigValue("cookieID-token-id"), tokenresponse.id_token, tokenrefresh.Username, tokenresponse.expires_in);
                    tokenaccess = DBCookie.LoadDBCookie(context, context.GetConfigValue("cookieID-token-access"));
                    context.LogDebug(this, string.Format("GetUserProfile - refresh -- tokenrefresh = {0} ; tokenaccess = {1}", tokenrefresh.Value, tokenaccess.Value));
                } catch (Exception) {
                    return(null);
                }
            }

            if (!string.IsNullOrEmpty(tokenaccess.Value))
            {
                OauthUserInfoResponse usrInfo = client.GetUserInfo(tokenaccess.Value);

                context.LogDebug(this, string.Format("GetUserProfile -- usrInfo"));

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

                context.LogDebug(this, string.Format("GetUserProfile -- usrInfo = {0}", usrInfo.sub));

                //Check if association auth / username exists
                int  userId = User.GetUserId(context, usrInfo.sub, authType);
                bool userHasAuthAssociated = userId != 0;

                //user has ldap auth associated to his account
                if (userHasAuthAssociated)
                {
                    //User exists, we load it
                    usr = UserTep.FromId(context, userId);
                    //test if TerradueCloudUsername was set
                    if (string.IsNullOrEmpty(usr.TerradueCloudUsername))
                    {
                        usr.LoadCloudUsername();
                        if (string.IsNullOrEmpty(usr.TerradueCloudUsername))
                        {
                            usr.TerradueCloudUsername = usrInfo.sub;
                            usr.StoreCloudUsername();
                        }
                    }

                    //update user infos
                    if (!string.IsNullOrEmpty(usrInfo.given_name))
                    {
                        usr.FirstName = usrInfo.given_name;
                    }
                    if (!string.IsNullOrEmpty(usrInfo.family_name))
                    {
                        usr.LastName = usrInfo.family_name;
                    }
                    if (!string.IsNullOrEmpty(usrInfo.zoneinfo))
                    {
                        usr.TimeZone = usrInfo.zoneinfo;
                    }
                    if (!string.IsNullOrEmpty(usrInfo.locale))
                    {
                        usr.Language = usrInfo.locale;
                    }

                    return(usr);
                }

                if (string.IsNullOrEmpty(usrInfo.email))
                {
                    throw new Exception("Null email returned by the Oauth mechanism, please contact support.");
                }

                //user does not have ldap auth associated to his account
                try {
                    //check if a user with the same email exists
                    usr = UserTep.FromEmail(context, usrInfo.email);

                    //user with the same email exists but not yet associated to ldap auth
                    usr.LinkToAuthenticationProvider(authType, usrInfo.sub);

                    return(usr);
                    //TODO: what about if user Cloud username is different ? force to new one ?
                } catch (Exception e) {
                    context.LogError(this, e.Message);
                }

                //user with this email does not exist, we should create it
                usr       = (UserTep)User.GetOrCreate(context, usrInfo.sub, authType);
                usr.Level = UserCreationDefaultLevel;

                //update user infos
                if (!string.IsNullOrEmpty(usrInfo.given_name))
                {
                    usr.FirstName = usrInfo.given_name;
                }
                if (!string.IsNullOrEmpty(usrInfo.family_name))
                {
                    usr.LastName = usrInfo.family_name;
                }
                if (!string.IsNullOrEmpty(usrInfo.email) && (TrustEmail || usrInfo.email_verifier))
                {
                    usr.Email = usrInfo.email;
                }
                if (!string.IsNullOrEmpty(usrInfo.zoneinfo))
                {
                    usr.TimeZone = usrInfo.zoneinfo;
                }
                if (!string.IsNullOrEmpty(usrInfo.locale))
                {
                    usr.Language = usrInfo.locale;
                }

                if (usr.Id == 0)
                {
                    usr.AccessLevel = EntityAccessLevel.Administrator;
                    NewUserCreated  = true;
                }

                usr.Store();

                usr.LinkToAuthenticationProvider(authType, usrInfo.sub);

                usr.TerradueCloudUsername = usrInfo.sub;
                usr.StoreCloudUsername();

                return(usr);
            }
            else
            {
            }

            context.LogDebug(this, string.Format("GetUserProfile -- return null"));

            return(null);
        }
Exemplo n.º 4
0
        public string GetResultDescriptionFromS3Link(IfyContext context, WpsJob job, string s3link)
        {
            var resultdescription = s3link;

            if (System.Configuration.ConfigurationManager.AppSettings["SUPERVISOR_WPS_STAGE_URL"] != null && !string.IsNullOrEmpty(s3link))
            {
                var            url        = System.Configuration.ConfigurationManager.AppSettings["SUPERVISOR_WPS_STAGE_URL"];
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["ProxyHost"]))
                {
                    webRequest.Proxy = TepUtility.GetWebRequestProxy();
                }
                var access_token = DBCookie.LoadDBCookie(context, System.Configuration.ConfigurationManager.AppSettings["SUPERVISOR_COOKIE_TOKEN_ACCESS"]).Value;
                webRequest.Headers.Set(HttpRequestHeader.Authorization, "Bearer " + access_token);
                webRequest.Timeout     = 10000;
                webRequest.Method      = "POST";
                webRequest.ContentType = "application/json";

                var shareUri    = job.GetJobShareUri(job.AppIdentifier);
                var publishlink = new Wps3Utils.SyndicationLink {
                    Href       = shareUri.AbsoluteUri,
                    Rel        = "external",
                    Type       = "text/html",
                    Title      = "Producer Link",
                    Attributes = new List <KeyValuePair <string, string> > {
                        new KeyValuePair <string, string>("level", "primary")
                    }
                };
                context.LogDebug(job, string.Format("publish request to supervisor - s3link = {0} ; jobUrl = {1} ; index = {2}", s3link, shareUri.AbsoluteUri, job.Owner.Username));
                string authBasicHeader = null;
                try {
                    if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["SUPERVISOR_FIXED_AUTH_HEADER"]))
                    {
                        authBasicHeader = System.Configuration.ConfigurationManager.AppSettings["SUPERVISOR_FIXED_AUTH_HEADER"];
                    }
                    else
                    {
                        var apikey = job.Owner.LoadApiKeyFromRemote();
                        authBasicHeader = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(job.Owner.Username + ":" + apikey));
                    }
                }catch (Exception e) {
                    context.LogError(this, "Error get apikey : " + e.Message);
                }

                var jsonurl = new SupervisorPublish
                {
                    Url = s3link,
                    AuthorizationHeader = authBasicHeader,
                    Index       = job.Owner.Username,
                    CreateIndex = true,
                    Categories  = new List <Wps3Utils.SyndicationCategory> {
                        new Wps3Utils.SyndicationCategory {
                            Name = "appId", Label = job.AppIdentifier, Scheme = ""
                        }
                    },
                    Links = new List <Wps3Utils.SyndicationLink> {
                        publishlink
                    }
                };

                var json = ServiceStack.Text.JsonSerializer.SerializeToString(jsonurl);
                context.LogDebug(this, string.Format("publish request to supervisor - json = {0}", json));
                EventFactory.LogWpsJob(context, job, "Job published", "portal_job_publish");
                try {
                    using (var streamWriter = new StreamWriter(webRequest.GetRequestStream())) {
                        streamWriter.Write(json);
                        streamWriter.Flush();
                        streamWriter.Close();

                        using (var httpResponse = (HttpWebResponse)webRequest.GetResponse()) {
                            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                            {
                                var location = httpResponse.Headers["Location"];
                                if (!string.IsNullOrEmpty(location))
                                {
                                    context.LogDebug(this, "location = " + location);
                                    resultdescription = new Uri(location, UriKind.RelativeOrAbsolute).AbsoluteUri;
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    context.LogError(job, "Error Create user product request to supervisor: " + e.Message);
                }
            }
            return(resultdescription);
        }