Exemplo n.º 1
0
        public object Get(GetStorageFilesRequestTep request)
        {
            var    context = string.IsNullOrEmpty(request.apikey) ? TepWebContext.GetWebContext(PagePrivileges.UserView) : TepWebContext.GetWebContext(PagePrivileges.EverybodyView);
            string result  = null;

            try {
                context.Open();
                context.LogInfo(this, string.Format("/store/{0}/{1} GET", request.repoKey, request.path));

                var apikey  = request.apikey ?? UserTep.FromId(context, context.UserId).GetSessionApiKey();
                var factory = new StoreFactory(context, apikey);

                Artifactory.Response.FileInfo info = factory.GetItemInfo(request.repoKey, request.path);
                info.Uri = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;
                result   = factory.Serializer.Serialize(info);

                context.Close();
            }catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }

            return(new HttpResult(result, Request.ContentType));
        }
Exemplo n.º 2
0
        public static List <OwsContextAtomEntry> GetRemoteWpsServiceEntriesFromUrl(IfyContext context, string href)
        {
            var result      = new List <OwsContextAtomEntry>();
            var httpRequest = (HttpWebRequest)WebRequest.Create(href);

            if (context.UserId != 0)
            {
                var user   = UserTep.FromId(context, context.UserId);
                var apikey = user.GetSessionApiKey();
                if (!string.IsNullOrEmpty(user.Username) && !string.IsNullOrEmpty(apikey))
                {
                    httpRequest.Headers.Set(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes(user.Username + ":" + apikey)));
                }
            }

            //TODO: manage case of /description
            //TODO: manage case of total result > 20
            using (var resp = httpRequest.GetResponse()) {
                using (var stream = resp.GetResponseStream()) {
                    var feed = ThematicAppCachedFactory.GetOwsContextAtomFeed(stream);
                    if (feed.Items != null)
                    {
                        foreach (OwsContextAtomEntry item in feed.Items)
                        {
                            result.Add(item);
                        }
                    }
                }
            }
            return(result);
        }
Exemplo n.º 3
0
        public object Get(AnalyticsCurrentUserRequestTep request)
        {
            var          context = TepWebContext.GetWebContext(PagePrivileges.UserView);
            WebAnalytics result  = new WebAnalytics();

            try {
                context.Open();
                context.LogInfo(this, string.Format("/analytics/user/current GET"));

                Analytics analytics = new Analytics(context, UserTep.FromId(context, context.UserId));
                analytics.AnalyseCollections  = false;
                analytics.AnalyseDataPackages = false;
                analytics.AnalyseJobs         = true;
                analytics.AnalyseServices     = false;
                analytics.Load(request.startdate, request.enddate);

                result = new WebAnalytics(analytics);

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(result);
        }
Exemplo n.º 4
0
        public object Put(PutMoveStorageItemRequestTep request)
        {
            var    context = string.IsNullOrEmpty(request.apikey) ? TepWebContext.GetWebContext(PagePrivileges.UserView) : TepWebContext.GetWebContext(PagePrivileges.EverybodyView);
            string result  = null;

            try {
                context.Open();
                context.LogInfo(this, string.Format("/store/move/{0}/{1}?to={2}&dry={3} PUT", request.srcRepoKey, request.srcPath, request.to, request.dry));

                var apikey  = request.apikey ?? UserTep.FromId(context, context.UserId).GetSessionApiKey();
                var factory = new StoreFactory(context, apikey);

                var to     = request.to.Trim('/');
                var toRepo = to.Substring(0, to.IndexOf('/'));
                var toPath = to.Substring(to.IndexOf('/') + 1);

                var info = factory.MoveItem(request.srcRepoKey, request.srcPath, toRepo, toPath, request.dry);
                result = factory.Serializer.Serialize(info);

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }

            return(new HttpResult(result, Request.ContentType));
        }
Exemplo n.º 5
0
        public object Get(GetDownloadStorageFileRequestTep request)
        {
            //var context = string.IsNullOrEmpty(request.apikey) ? TepWebContext.GetWebContext(PagePrivileges.UserView) : TepWebContext.GetWebContext(PagePrivileges.EverybodyView);
            var    context = TepWebContext.GetWebContext(PagePrivileges.EverybodyView);
            Stream result  = null;

            try {
                context.Open();
                context.LogInfo(this, string.Format("/store/download/{0}/{1} GET", request.repoKey, request.path));

                var apikey  = request.apikey ?? (context.UserId > 0 ? UserTep.FromId(context, context.UserId).GetSessionApiKey() : null);
                var factory = new StoreFactory(context, apikey);

                result = factory.DownloadItem(request.repoKey, request.path);

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }

            var filename = request.path.Substring(request.path.LastIndexOf('/') + 1);

            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename));
            return(new HttpResult(result, "application/octet"));
        }
Exemplo n.º 6
0
        public void RefreshCachedApp(string uid)
        {
            this.LogInfo(string.Format("RefreshCachedApps -- Get public apps"));
            var apps = new EntityList <ThematicApplicationCached>(context);

            apps.SetFilter("UId", uid);
            apps.Load();
            if (apps.Count == 1)
            {
                var app     = apps.GetItemsAsList()[0];
                var entries = app.Feed;
                if (entries == null)
                {
                    entries = ThematicAppCachedFactory.GetOwsContextAtomFeed(app.TextFeed);
                }
                var itemFeed = entries.Items.First();
                var link     = itemFeed.Links.FirstOrDefault(l => l.RelationshipType == "self");
                if (link == null)
                {
                    return;
                }
                var url   = link.Uri.AbsoluteUri;
                var urib  = new UriBuilder(url);
                var query = HttpUtility.ParseQueryString(urib.Query);

                //add user apikey
                var user   = UserTep.FromId(context, context.UserId);
                var apikey = user.GetSessionApiKey();
                if (!string.IsNullOrEmpty(apikey))
                {
                    query.Set("apikey", apikey);
                }

                //add random for cache
                var random = new Random();
                query.Set("random", random.Next() + "");
                var queryString = Array.ConvertAll(query.AllKeys, key => string.Format("{0}={1}", key, query[key]));
                urib.Query = string.Join("&", queryString);
                url        = urib.Uri.AbsoluteUri;

                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
                using (var resp = httpRequest.GetResponse())
                {
                    using (var stream = resp.GetResponseStream())
                    {
                        var feed  = GetOwsContextAtomFeed(stream);
                        var entry = feed.Items.First();
                        if (feed.Items != null && feed.Items.Count() == 1)
                        {
                            app.Feed       = feed;
                            app.TextFeed   = GetOwsContextAtomFeedAsString(feed);
                            app.Searchable = GetSearchableTextFromAtomEntry(entry);
                            app.LastUpdate = entry.LastUpdatedTime.DateTime == DateTime.MinValue ? DateTime.UtcNow : entry.LastUpdatedTime.DateTime;
                            app.Store();
                            this.LogInfo(string.Format("ThematicAppCachedFactory -- Cached '{0}'", app.UId));
                        }
                    }
                }
            }
        }
Exemplo n.º 7
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);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Update the specified user.
        /// </summary>
        /// <param name="request">Request.</param>
        /// <returns>the user</returns>
        public object Put(UserUpdateRequestTep request)
        {
            var        context = TepWebContext.GetWebContext(PagePrivileges.UserView);
            WebUserTep result;

            try {
                context.Open();
                context.LogInfo(this, string.Format("/user PUT Id='{0}'", request.Id > 0 ? request.Id + "" : request.Identifier));
                UserTep user = (request.Id == 0 ? (!string.IsNullOrEmpty(request.Identifier) ? UserTep.FromIdentifier(context, request.Identifier) : null) : UserTep.FromId(context, request.Id));
                if (context.UserId != user.Id && context.AccessLevel != EntityAccessLevel.Administrator)
                {
                    throw new Exception("Action not allowed");
                }
                var level = user.Level;
                user       = request.ToEntity(context, user);
                user.Level = level;//we can only change the level from the dedicated request (admin only)
                user.Store();
                context.LogDebug(this, string.Format("User '{0}' has been updated", user.Username));
                result = new WebUserTep(context, user);
                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(result);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Post the specified request.
        /// </summary>
        /// <param name="request">Request.</param>
        public object Post(UserCreateRequestTep request)
        {
            var        context = TepWebContext.GetWebContext(PagePrivileges.UserView);
            WebUserTep result;

            try{
                context.Open();

                UserTep user = (request.Id == 0 ? null : UserTep.FromId(context, request.Id));
                user = request.ToEntity(context, user);
                if (request.Id != 0 && context.UserLevel == UserLevel.Administrator)
                {
                    user.AccountStatus = AccountStatusType.Enabled;
                }
                else
                {
                    user.AccountStatus = AccountStatusType.PendingActivation;
                }

                user.IsNormalAccount = true;
                user.Level           = UserLevel.User;

                user.Store();
                context.LogInfo(this, string.Format("/user POST Id='{0}'", user.Id));
                context.LogDebug(this, string.Format("User '{0}' has been created", user.Username));
                result = new WebUserTep(context, user);
                context.Close();
            }catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(result);
        }
Exemplo n.º 10
0
        public object Post(AddGithubSSHKeyToCurrentUser request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);
            WebGithubProfile result;

            try {
                context.Open();
                context.LogInfo(this, string.Format("/github/sshkey POST"));

                GithubProfile user    = GithubProfile.FromId(context, context.UserId);
                UserTep       userTep = UserTep.FromId(context, context.UserId);
                userTep.LoadSSHPubKey();
                user.PublicSSHKey = userTep.SshPubKey;
                GithubClient githubClient = new GithubClient(context);
                if (!user.IsAuthorizationTokenValid())
                {
                    throw new UnauthorizedAccessException("Invalid token");
                }
                if (user.PublicSSHKey == null)
                {
                    throw new UnauthorizedAccessException("No available public ssh key");
                }
                githubClient.AddSshKey("Terradue ssh key", user.PublicSSHKey, user.Name, user.Token);
                context.LogDebug(this, string.Format("User {0} added Terradue ssh key to his github account", userTep.Username));
                result = new WebGithubProfile(user);
                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }

            return(result);
        }
Exemplo n.º 11
0
        public object Put(UpdateGithubUser request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);
            WebGithubProfile result;

            try {
                context.Open();
                context.LogInfo(this, string.Format("/github/user PUT Id='{0}'", request.Id));
                GithubProfile user = GithubProfile.FromId(context, request.Id);
                user = request.ToEntity(context, user);
                user.Store();
                user.Load(); //to get information from Github
                UserTep userTep = UserTep.FromId(context, context.UserId);
                userTep.LoadSSHPubKey();
                user.PublicSSHKey = userTep.SshPubKey;
                context.LogDebug(this, string.Format("Github account of user {0} has been updated", userTep.Username));
                result = new WebGithubProfile(user);
                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }

            return(result);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Create a user event (metrics)
        /// </summary>
        /// <returns></returns>
        public async System.Threading.Tasks.Task <Event> GetLogEvent(UserTep usr, string eventid, string message = null)
        {
            try
            {
                var properties = new Dictionary <string, object>();
                properties.Add("affiliation", usr.Affiliation);
                properties.Add("country", usr.Country);

                var logevent = new Event
                {
                    EventId = eventid,
                    Project = EventFactory.EventLogConfig.Settings["project"] != null ? EventFactory.EventLogConfig.Settings["project"].Value : "",
                    Status  = usr.Level.ToString(),
                    // Durations = durations,
                    Transmitter = EventFactory.EventLogConfig.Settings["transmitter"] != null ? EventFactory.EventLogConfig.Settings["transmitter"].Value : "",
                    Message     = message,
                    Item        = new EventItem
                    {
                        Created    = usr.GetFirstLoginDate(),
                        Updated    = usr.GetLastLoginDate(),
                        Id         = usr.Username,
                        Title      = usr.Caption,
                        Type       = "portal_user",
                        Properties = properties
                    }
                };

                return(logevent);
            }catch (Exception e) {
                context.LogError(usr, "Log event error: " + e.Message);
            }
            return(null);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Get the specified request.
        /// </summary>
        /// <param name="request">Request.</param>
        public object Get(UserGetGroupsRequestTep request)
        {
            List <WebGroup> result = new List <WebGroup>();

            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            try {
                context.Open();
                context.LogInfo(this, string.Format("/user/{{usrId}}/group PUT usrId='{0}'", request.UsrId));

                UserTep    user = UserTep.FromIdentifier(context, request.UsrId);
                List <int> ids  = user.GetGroups();

                List <Group> groups = new List <Group>();
                foreach (int id in ids)
                {
                    groups.Add(Group.FromId(context, id));
                }

                foreach (Group grp in groups)
                {
                    result.Add(new WebGroup(grp));
                }

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(result);
        }
Exemplo n.º 14
0
        public object Get(AnalyticsRequestTep request)
        {
            var          context = TepWebContext.GetWebContext(PagePrivileges.EverybodyView);
            WebAnalytics result  = new WebAnalytics();

            try {
                context.Open();
                context.LogInfo(this, string.Format("/analytics GET - type='{0}', identifier='{1}'", request.Type, request.Identifier));

                Analytics analytics = null;

                if (context.UserId == 0)
                {
                    request.Type = "all";
                }

                switch (request.Type)
                {
                case "user":
                    analytics = new Analytics(context, UserTep.FromIdentifier(context, request.Identifier));
                    analytics.Load(request.startdate, request.enddate);
                    break;

                case "community":
                    analytics = new Analytics(context, ThematicCommunity.FromIdentifier(context, request.Identifier));
                    analytics.Load(request.startdate, request.enddate);
                    break;

                case "group":
                    analytics = new Analytics(context, Group.FromIdentifier(context, request.Identifier));
                    analytics.Load(request.startdate, request.enddate);
                    break;

                case "service":
                    analytics = new Analytics(context, Service.FromIdentifier(context, request.Identifier));
                    analytics.Load(request.startdate, request.enddate);
                    break;

                case "all":
                    analytics = new Analytics(context);
                    analytics.Load(request.startdate, request.enddate);
                    break;

                default:
                    break;
                }
                if (analytics != null)
                {
                    result = new WebAnalytics(analytics);
                }

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(result);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Tos the entity.
        /// </summary>
        /// <returns>The entity.</returns>
        /// <param name="context">Context.</param>
        public UserTep ToEntity(IfyContext context, UserTep input)
        {
            UserTep user = (input == null ? new UserTep(context) : input);

            user = (UserTep)base.ToEntity(context, user);

            return(user);
        }
Exemplo n.º 16
0
        private void Init()
        {
            //Create users
            UserTep usr1 = new UserTep(context);

            usr1.Username = "******";
            usr1.Store();

            UserTep usr2 = new UserTep(context);

            usr2.Username = "******";
            usr2.Store();

            UserTep usr3 = new UserTep(context);

            usr3.Username = "******";
            usr3.Store();

            UserTep usr4 = new UserTep(context);

            usr4.Username = "******";
            usr4.Store();

            //create domains
            Domain domain = new Domain(context);

            domain.Identifier = "myDomainTest";
            domain.Kind       = DomainKind.Public;
            domain.Store();

            Domain domain2 = new Domain(context);

            domain2.Identifier = "otherDomainTest";
            domain2.Kind       = DomainKind.Hidden;
            domain2.Store();

            Role role = new Role(context);

            role.Identifier = "member-test";
            role.Store();

            role.IncludePrivilege(Privilege.FromIdentifier(context, "wpsjob-v"));
            role.IncludePrivilege(Privilege.FromIdentifier(context, "wpsjob-s"));

            //Add users in the domain
            role.GrantToUser(usr1, domain);
            role.GrantToUser(usr2, domain);
            role.GrantToUser(usr3, domain);
            role.GrantToUser(usr3, domain2);

            //create community
            ThematicCommunity community1 = new ThematicCommunity(context);

            community1.Identifier = "community-public-1";
            community1.Kind       = DomainKind.Public;
            community1.Store();
            community1.SetOwner(usr3);
        }
Exemplo n.º 17
0
        /// <summary>
        /// Get the specified request.
        /// </summary>
        /// <param name="request">Request.</param>
        public object Get(DataPackagesSearchRequest request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.EverybodyView);
            IOpenSearchResultCollection result = null;

            try {
                context.Open();
                context.LogInfo(this, string.Format("/data/package/search GET"));

                EntityList <Terradue.Tep.DataPackage> datapackages = new EntityList <DataPackage>(context);
                if (!string.IsNullOrEmpty(request.Key))
                {
                    UserTep user = UserTep.FromApiKey(context, request.Key);
                    datapackages.UserId = user.Id;
                    context.AccessLevel = EntityAccessLevel.Privilege;
                }
                datapackages.SetFilter("Kind", RemoteResourceSet.KINDRESOURCESETNORMAL.ToString());

                // Load the complete request
                HttpRequest      httpRequest = HttpContext.Current.Request;
                OpenSearchEngine ose         = MasterCatalogue.OpenSearchEngine;

                // the opensearch cache system uses the query parameters
                // we add to the parameters the filters added to the load in order to avoir wrong cache
                // we use 't2-' in order to not interfer with possibly used query parameters
                var qs = new NameValueCollection(Request.QueryString);
                foreach (var filter in datapackages.FilterValues)
                {
                    qs.Add("t2-" + filter.Key.FieldName, filter.Value.ToString());
                }

                if (qs["visibility"] != null && qs["visibility"] != "all")
                {
                    datapackages.AccessLevel = EntityAccessLevel.Privilege;
                }

                if (context.UserLevel == UserLevel.Administrator && (qs["visibility"] == null || qs["visibility"] != "owned"))
                {
                    datapackages.SetFilter("Identifier", "!_index_*,!_series_*,!_products_*");
                }

                Type type = OpenSearchFactory.ResolveTypeFromRequest(httpRequest.QueryString, httpRequest.Headers, ose);
                result = ose.Query(datapackages, qs, type);

                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }

            return(new HttpResult(result.SerializeToString(), result.ContentType));
        }
Exemplo n.º 18
0
        public object Post(PostDiscourseTopic request)
        {
            var    context = TepWebContext.GetWebContext(PagePrivileges.UserView);
            string result;

            try {
                context.Open();
                context.LogInfo(this, string.Format("/discourse/posts POST community='{0}'{1}{2}",
                                                    request.communityIdentifier,
                                                    !string.IsNullOrEmpty(request.subject) ? ", subject='" + request.subject + "'" : "",
                                                    !string.IsNullOrEmpty(request.body) ? ", body='" + request.body + "'" : ""
                                                    ));

                if (string.IsNullOrEmpty(request.subject))
                {
                    throw new Exception("Unable to post new topic, subject is null");
                }
                if (string.IsNullOrEmpty(request.body))
                {
                    throw new Exception("Unable to post new topic, body is null");
                }

                var community       = ThematicCommunity.FromIdentifier(context, request.communityIdentifier);
                var discussCategory = community.DiscussCategory;
                if (string.IsNullOrEmpty(discussCategory))
                {
                    throw new Exception("Unable to post new topic, the selected community has no Discuss category associated");
                }

                var user = UserTep.FromId(context, context.UserId);
                if (string.IsNullOrEmpty(user.TerradueCloudUsername))
                {
                    throw new Exception("Unable to post new topic, please set first your Terradue Cloud username");
                }

                var discussClient = new DiscussClient(context.GetConfigValue("discussBaseUrl"), context.GetConfigValue("discussApiKey"), user.TerradueCloudUsername);
                var category      = discussClient.GetCategory(discussCategory);
                if (category == null)
                {
                    throw new Exception("Unable to post new topic, the selected community has no valid Discuss category associated");
                }
                var catId = category.id;

                var response = discussClient.PostTopic(catId, request.subject, request.body);
                result = string.Format("{0}/t/{1}/{2}", discussClient.Host, response.topic_slug, response.topic_id);
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(new WebService.Model.WebResponseString(result));
        }
Exemplo n.º 19
0
        /// <summary>
        /// Get the specified request.
        /// </summary>
        /// <param name="request">Request.</param>
        public object Get(UserCurrentIsLoggedRequestTep request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            try {
                context.Open();
                UserTep.UpdateUserSessionEndTime(context, context.UserId);
            } catch (Exception) {
                return(new WebResponseBool(false));
            }
            context.Close();
            return(new WebResponseBool(true));
        }
Exemplo n.º 20
0
        /// <summary>
        /// Creates the or update cached apps from user.
        /// </summary>
        /// <returns>The or update cached apps from user.</returns>
        /// <param name="user">User.</param>
        public List <int> CreateOrUpdateCachedAppsFromUser(UserTep user)
        {
            List <int> upIds  = new List <int>();
            var        app    = user.GetPrivateThematicApp();
            var        domain = user.GetPrivateDomain();

            foreach (var appItem in app.Items)
            {
                var ids = CreateOrUpdateCachedAppFromUrl(appItem.Location, domain.Id);
                upIds.AddRange(ids);
            }
            return(upIds);
        }
Exemplo n.º 21
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Terradue.Tep.WebServer.WebUserTep"/> class.
        /// </summary>
        /// <param name="entity">Entity.</param>
        public WebUserTep(IfyWebContext context, UserTep entity, bool umsso = false) : base(entity)
        {
            if (umsso)
            {
                AuthenticationType umssoauthType = IfyWebContext.GetAuthenticationType(typeof(UmssoAuthenticationType));
                var umssoUser = umssoauthType.GetUserProfile(context, HttpContext.Current.Request, false);
                if (umssoUser != null)
                {
                    this.UmssoEmail = umssoUser.Email;
                }
            }

            //only current user can know the api key
            if (context.UserId == entity.Id)
            {
                this.ApiKey         = entity.ApiKey;
                this.T2ProfileError = HttpContext.Current.Session["t2profileError"] as string;
                if ((string.IsNullOrEmpty(entity.Affiliation) || string.IsNullOrEmpty(entity.Country) || string.IsNullOrEmpty(entity.FirstName) || string.IsNullOrEmpty(entity.LastName)))
                {
                    this.T2ProfileError += (string.IsNullOrEmpty(this.T2ProfileError) ? "" : "\n") + "Profile not complete";
                }
                this.T2ApiKey = entity.GetSessionApiKey();
            }

            if (context.UserId == entity.Id || context.UserLevel == UserLevel.Administrator)
            {
                this.T2Username = entity.TerradueCloudUsername;
                if (context.GetConfigBooleanValue("accounting-enabled"))
                {
                    this.Balance = entity.GetAccountingBalance();
                }
                this.Roles = GetUserCommunityRoles(context, entity);
                if (context.UserLevel == UserLevel.Administrator)
                {
                    if (entity.RegistrationDate == DateTime.MinValue)
                    {
                        entity.LoadRegistrationInfo();
                    }
                    this.RegistrationDate = entity.RegistrationDate;
                }
            }
            else
            {
                this.Email         = null;
                this.Affiliation   = null;
                this.Level         = 0;
                this.AccountStatus = 0;
                this.DomainId      = null;
            }
        }
Exemplo n.º 22
0
        public object Get(ThematicAppCacheRequestTep request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            context.Open();
            try {
                context.LogInfo(this, string.Format("/apps/cache GET"));
                var appFactory = new ThematicAppCachedFactory(context);
                if (!string.IsNullOrEmpty(request.Uid))
                {
                    //refresh only a given app
                    appFactory.RefreshCachedApp(request.Uid);
                }
                else if (!string.IsNullOrEmpty(request.Username))
                {
                    //refresh only for private apps
                    var user = UserTep.FromIdentifier(context, request.Username);
                    if (user.Id == context.UserId)
                    {
                        appFactory.RefreshCachedAppsForUser(user);
                    }
                }
                else if (!string.IsNullOrEmpty(request.Community))
                {
                    //refresh only for community apps
                    var community = ThematicCommunity.FromIdentifier(context, request.Community);
                    if (community.CanUserManage(context.UserId))
                    {
                        appFactory.RefreshCachedAppsForCommunity(community);
                    }
                }
                else
                {
                    //user should be admin
                    if (context.UserLevel == UserLevel.Administrator)
                    {
                        //case TEP -- we don't want user privates apps to be cached
                        appFactory.RefreshCachedApps(false, true, true);
                    }
                }
                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(new WebResponseBool(true));
        }
Exemplo n.º 23
0
        public object Post(PostStorageFilesRequestTep request)
        {
            if (request.repoKey == null)
            {
                var segments = base.Request.PathInfo.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                request.repoKey = segments[1];
                request.path    = base.Request.PathInfo.Substring(base.Request.PathInfo.IndexOf(request.repoKey + "/") + request.repoKey.Length + 1);
            }
            if (request.apikey == null)
            {
                request.apikey = base.Request.QueryString["apikey"];
            }

            var context = string.IsNullOrEmpty(request.apikey) ? TepWebContext.GetWebContext(PagePrivileges.UserView) : TepWebContext.GetWebContext(PagePrivileges.EverybodyView);

            context.LogInfo(this, string.Format("/store/{0}/{1} POST", request.repoKey, request.path));

            string path = System.Configuration.ConfigurationManager.AppSettings["UploadTmpPath"] ?? "/tmp";

            try {
                context.Open();

                var apikey  = request.apikey ?? UserTep.FromId(context, context.UserId).GetSessionApiKey();
                var factory = new StoreFactory(context, apikey);

                var filename = path + "/" + request.path.Substring(request.path.LastIndexOf("/") + 1);
                using (var stream = new MemoryStream()) {
                    if (this.RequestContext.Files.Length > 0)
                    {
                        var uploadedFile = this.RequestContext.Files[0];
                        uploadedFile.SaveTo(filename);
                    }
                    else
                    {
                        using (var fileStream = File.Create(filename)) {
                            request.RequestStream.CopyTo(fileStream);
                        }
                    }
                    factory.UploadFile(request.repoKey, request.path, filename);
                }
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            context.Close();
            return(new WebResponseBool(true));
        }
Exemplo n.º 24
0
        private void Init()
        {
            //Create users
            UserTep usr1 = new UserTep(context);

            usr1.Username = "******";
            usr1.Store();

            UserTep usr2 = new UserTep(context);

            usr2.Username = "******";
            usr2.Store();

            UserTep usr3 = new UserTep(context);

            usr3.Username = "******";
            usr3.Store();

            //create communities
            ThematicCommunity community1 = new ThematicCommunity(context);

            community1.Identifier = "community-public-1";
            community1.Kind       = DomainKind.Public;
            community1.Store();
            community1.SetOwner(usr2);

            ThematicCommunity community2 = new ThematicCommunity(context);

            community2.Identifier = "community-private-1";
            community2.Kind       = DomainKind.Hidden;
            community2.Store();
            community2.SetOwner(usr2);

            ThematicCommunity community3 = new ThematicCommunity(context);

            community3.Identifier = "community-private-2";
            community3.Kind       = DomainKind.Hidden;
            community3.Store();
            community3.SetOwner(usr2);

            ThematicCommunity community4 = new ThematicCommunity(context);

            community4.Identifier = "community-public-2";
            community4.Kind       = DomainKind.Public;
            community4.Store();
            community4.SetOwner(usr2);
        }
Exemplo n.º 25
0
        public object Get(WpsJobSearchRequestTep request)
        {
            var context = TepWebContext.GetWebContext(PagePrivileges.EverybodyView);

            context.Open();
            context.LogInfo(this, string.Format("/job/wps/search GET"));

            EntityList <WpsJob> wpsjobs = new EntityList <WpsJob>(context);

            wpsjobs.AddSort("Id", SortDirection.Descending);
            wpsjobs.IncludeOwnerFieldsInSearch = true;

            // Load the complete request
            HttpRequest httpRequest = HttpContext.Current.Request;
            var         qs          = new NameValueCollection(httpRequest.QueryString);

            OpenSearchEngine ose = MasterCatalogue.OpenSearchEngine;

            if (qs["visibility"] != null && qs["visibility"] != "all")
            {
                wpsjobs.AccessLevel = EntityAccessLevel.Privilege;
            }

            if (!string.IsNullOrEmpty(qs["key"]))
            {
                try{
                    UserTep user = UserTep.FromApiKey(context, qs["key"]);
                    wpsjobs.UserId      = user.Id;
                    context.AccessLevel = EntityAccessLevel.Privilege;
                }catch (Exception) {}
            }

            if (string.IsNullOrEmpty(qs["id"]) && string.IsNullOrEmpty(qs["uid"]) && string.IsNullOrEmpty(qs["archivestatus"]))
            {
                qs.Set("archivestatus", (int)WpsJobArchiveStatus.NOT_ARCHIVED + "");
            }

            Type responseType = OpenSearchFactory.ResolveTypeFromRequest(httpRequest.QueryString, httpRequest.Headers, ose);
            IOpenSearchResultCollection osr = ose.Query(wpsjobs, qs, responseType);

            OpenSearchFactory.ReplaceOpenSearchDescriptionLinks(wpsjobs, osr);
//            OpenSearchFactory.ReplaceSelfLinks(wpsjobs, httpRequest.QueryString, osr.Result, EntrySelfLinkTemplate);

            context.Close();
            return(new HttpResult(osr.SerializeToString(), osr.ContentType));
        }
Exemplo n.º 26
0
        public object Put(UpdateProfileFromRemoteTep request)
        {
            WebUserTep result  = null;
            var        context = TepWebContext.GetWebContext(PagePrivileges.AdminOnly);

            context.Open();
            var usr = UserTep.FromIdentifier(context, request.Identifier);

            try
            {
                usr.LoadProfileFromRemote();
                result = new WebUserTep(context, usr);
            }catch (Exception e) {
                context.LogError(this, e.Message + " - " + e.StackTrace);
            }
            context.Close();
            return(result);
        }
Exemplo n.º 27
0
        public static async System.Threading.Tasks.Task LogUser(IfyContext context, UserTep usr, string eventid, string message)
        {
            if (EventLogConfig == null || EventLogConfig.Settings == null || EventLogConfig.Settings.Count == 0)
            {
                context.LogError(context, "Log error : missing configuration");
                return;
            }

            IEventUserLogger logger = GetUserLogger(context);

            if (logger != null)
            {
                var logevent = await logger.GetLogEvent(usr, eventid, message);

                context.LogInfo(context, string.Format("Log event (user) ; event id = {0} ; user id = {1}", logevent.EventId, usr.Username));
                await Log(context, logevent);
            }
        }
Exemplo n.º 28
0
        public object Get(ThematicAppCheckAvailabilityRequest request)
        {
            var  context = TepWebContext.GetWebContext(PagePrivileges.UserView);
            bool result  = false;

            context.Open();
            try {
                context.LogInfo(this, string.Format("/apps/available GET"));
                var user   = UserTep.FromId(context, context.UserId);
                var apikey = user.GetSessionApiKey();
                result = !CatalogueFactory.CheckIdentifierExists(context, request.Index, request.Uid, apikey);
                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(new WebResponseBool(result));
        }
Exemplo n.º 29
0
        public object Post(UserCurrentCreateSSORequestTep request)
        {
            WebUserTep result;
            var        context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            try {
                context.Open();
                context.LogInfo(this, string.Format("/user/current/sso POST"));
                UserTep user = UserTep.FromId(context, context.UserId);
                user.CreateSSOAccount(request.Password);
                result = new WebUserTep(context, user);
                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(result);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Get the specified request.
        /// </summary>
        /// <param name="request">Request.</param>
        public object Get(UserGetCurrentSSORequestTep request)
        {
            WebUserTep result;
            var        context = TepWebContext.GetWebContext(PagePrivileges.UserView);

            try {
                context.Open();
                context.LogInfo(this, string.Format("/user/current/sso GET"));
                UserTep user = UserTep.FromId(context, context.UserId);
                //user.FindTerradueCloudUsername();
                result = new WebUserTep(context, user);
                context.Close();
            } catch (Exception e) {
                context.LogError(this, e.Message, e);
                context.Close();
                throw e;
            }
            return(result);
        }