void InitUser(IServiceBase authService, GXAmiUser user)
        {
            IAuthSession s = authService.GetSession(false);

            s.Id              = user.Id.ToString();
            s.UserAuthId      = Guid.NewGuid().ToString();
            s.UserName        = user.Name;
            s.IsAuthenticated = true;
            s.Roles           = new List <string>();
            s.Roles.Add(user.AccessRightsAsInt.ToString());
        }
Exemplo n.º 2
0
        void HandleUser(GXAmiUser user, GXEventsItem e)
        {
            ulong mask = (ulong)((int)e.Target << 16 | (int)e.Action);

            //Find is anyone interested from this user event.
            foreach (GXSession it in Sessions)
            {
                foreach (GXEvent e1 in it.NotifyClients)
                {
                    if (e1.UserID != 0 && (mask & e1.Mask) != 0)
                    {
                        //Notify only super admin and user from the task.
                        if (e1.SuperAdmin || e1.UserID == user.Id)
                        {
                            e1.Rows.Add(e);
                            it.Received.Set();
                        }
                    }
                }
            }
        }
Exemplo n.º 3
0
		public GXUsersResponse(GXAmiUser[] users)
		{
			this.Users = users;
		}
        /// <summary>
        /// Is user allowed to use service.
        /// </summary>
        /// <param name="authService"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
        {
            GXAmiUser user;
            OrmLiteConnectionFactory f = authService.TryResolve<IDbConnectionFactory>() as OrmLiteConnectionFactory;                                    
            //Connection factory is null when we are configure server at first time.
            if (f == null || f.ConnectionString == null)
            {
                return true;
            }
            try
            {
                using (IDbConnection Db = f.OpenDbConnection())
                {
                    lock (Db)
                    {
                        if (!GuruxAMI.Service.GXManagementService.IsDatabaseCreated(Db))
                        {
#if !SS4
                            string[] items = RestPath.GetPathPartsForMatching(authService.RequestContext.PathInfo);
#else
                        string[] items = RestPath.GetPathPartsForMatching(authService.Request.PathInfo);
#endif
                            string target = items[items.Length - 1];
                            if (string.Compare(target, typeof(GXIsDatabaseCreatedRequest).Name, true) == 0 ||
                                string.Compare(target, typeof(GXCreateTablesRequest).Name, true) == 0 ||
                                string.Compare(target, typeof(GXDropTablesRequest).Name, true) == 0)
                            {
                                user = new GXAmiUser("gurux", "gurux", UserAccessRights.SuperAdmin);
                                user.Id = 1;
                                InitUser(authService, user);
                                return true;
                            }
                            return false;
                        }
                        List<GXAmiUser> users = Db.Select<GXAmiUser>(q => q.Name == userName && q.Password == password);
                        if (users.Count != 1)
                        {
                            //If known DC try to get new tasks, add new task, mark task claimed or add device exception.
                            Guid guid;
#if !SS4
                            string[] items = RestPath.GetPathPartsForMatching(authService.RequestContext.PathInfo);
#else
                        string[] items = RestPath.GetPathPartsForMatching(authService.Request.PathInfo);
#endif
                            string target = items[items.Length - 1];
                            if (items != null && items.Length != 0)
                            {
                                if (string.Compare(target, typeof(GXEventsRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXEventsRegisterRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXEventsUnregisterRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXTaskDeleteRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXTasksRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXTaskUpdateRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXTasksClaimRequest).Name, true) == 0 ||                                    
                                    string.Compare(target, typeof(GXTraceLevelRequest).Name, true) == 0)
                                {
                                    //If DC register first time and starts to listen events.
                                    if (IsGuid(userName, out guid))
                                    {
                                        //If known DC wants to listen events.
                                        List<GXAmiDataCollector> list = Db.Select<GXAmiDataCollector>(p => p.Guid == guid);
                                        if (list.Count == 1)
                                        {
                                            IAuthSession s = authService.GetSession(false);
                                            s.Id = userName;
                                            s.UserAuthId = Guid.NewGuid().ToString();
                                            s.UserName = userName;
                                            s.IsAuthenticated = true;
                                            s.Roles = new List<string>();
                                            s.Roles.Add("0");
                                            return true;
                                        }
                                        return false;
                                    }
                                    return false;
                                }
                                else if (string.Compare(target, typeof(GXDataCollectorUpdateRequest).Name, true) == 0 &&
                                    IsGuid(userName, out guid))
                                {
                                    if (guid == Guid.Empty)
                                    {
                                        /* TODO:
                                        IAuthSession s = authService.GetSession(false);
                                        s.Id = userName;
                                        s.UserAuthId = Guid.NewGuid().ToString();
                                        s.UserName = userName;
                                        s.IsAuthenticated = true;
                                        s.Roles = new List<string>();
                                        s.Roles.Add("0");
                                         * */
                                        return true;
                                    }
                                    //If DC updates itself.
                                    List<GXAmiDataCollector> list = Db.Select<GXAmiDataCollector>(p => p.Guid == guid);
                                    if (list.Count == 1)
                                    {
                                        IAuthSession s = authService.GetSession(false);
                                        s.Id = userName;
                                        s.UserAuthId = Guid.NewGuid().ToString();
                                        s.UserName = userName;
                                        s.IsAuthenticated = true;
                                        s.Roles = new List<string>();
                                        s.Roles.Add("0");
                                        return true;
                                    }
                                    return false;
                                }
                                //If data collector wants to get data from itself by Guid.
                                else if (string.Compare(target, typeof(GXDataCollectorsRequest).Name, true) == 0 &&
                                    IsGuid(userName, out guid))
                                {
                                    List<GXAmiDataCollector> list = Db.Select<GXAmiDataCollector>(p => p.Guid == guid);
                                    if (list.Count == 1)
                                    {
                                        IAuthSession s = authService.GetSession(false);
                                        s.Id = userName;
                                        s.UserAuthId = Guid.NewGuid().ToString();
                                        s.UserName = userName;
                                        s.IsAuthenticated = true;
                                        s.Roles = new List<string>();
                                        s.Roles.Add("0");
                                        return true;
                                    }
                                    return false;                                 
                                }
                                return false;
                            }
                        }
                        user = users[0];
                        InitUser(authService, user);
                    }
                }
            }            
            catch (Exception ex)
            {
                GuruxAMI.Server.AppHost.ReportError(ex);
                try
                {
                    if (!System.Diagnostics.EventLog.SourceExists("GuruxAMI"))
                    {
                        System.Diagnostics.EventLog.CreateEventSource("GuruxAMI", "Application");
                    }
                    System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
                    appLog.Source = "GuruxAMI";
                    appLog.WriteEntry(ex.Message);
                }
                catch (System.Security.SecurityException)
                {
                    //Security exception is thrown if GuruxAMI source is not exists and it's try to create without administrator privilege.
                    //Just skip this, but errors are not write to eventlog.
                }
                throw ex;
            }
            return true;
        }
 void InitUser(IServiceBase authService, GXAmiUser user)
 {
     IAuthSession s = authService.GetSession(false);
     s.Id = user.Id.ToString();
     s.UserAuthId = Guid.NewGuid().ToString();
     s.UserName = user.Name;
     s.IsAuthenticated = true;
     s.Roles = new List<string>();
     s.Roles.Add(user.AccessRightsAsInt.ToString());
 }
Exemplo n.º 6
0
        /// <summary>
        /// Create default tables and set initial settings.
        /// </summary>
        /// <param name="Db"></param>
        static public void InitializeDB(IDbConnection Db, ProgressEventHandler progress, string userName, string password)
        {
            lock (Db)
            {
                try
                {
                    int index = 0;
                    CreateTable <GXAmiSettings>(Db, ref index, progress);
                    CreateTable <GXAmiUser>(Db, ref index, progress);
                    CreateTable <GXAmiUserGroup>(Db, ref index, progress);
                    CreateTable <GXAmiUserGroupUser>(Db, ref index, progress);
                    CreateTable <GXAmiDeviceGroup>(Db, ref index, progress);
                    CreateTable <GXAmiDeviceProfile>(Db, ref index, progress);
                    CreateTable <GXAmiDevice>(Db, ref index, progress);
                    CreateTable <GXAmiMediaType>(Db, ref index, progress);
                    CreateTable <GXAmiDeviceGroup>(Db, ref index, progress);
                    CreateTable <GXAmiUserGroupDeviceGroup>(Db, ref index, progress);
                    CreateTable <GXAmiDeviceGroupDevice>(Db, ref index, progress);
                    CreateTable <GXAmiParameterTemplate>(Db, ref index, progress);
                    CreateTable <GXAmiParameter>(Db, ref index, progress);
                    CreateTable <GXAmiPropertyTemplate>(Db, ref index, progress);
                    CreateTable <GXAmiProperty>(Db, ref index, progress);
                    CreateTable <GXAmiValueItem>(Db, ref index, progress);
                    CreateTable <GXAmiCategoryTemplate>(Db, ref index, progress);
                    CreateTable <GXAmiCategory>(Db, ref index, progress);
                    CreateTable <GXAmiDataTableTemplate>(Db, ref index, progress);
                    CreateTable <GXAmiDataTable>(Db, ref index, progress);
                    CreateTable <GXAmiDataRow>(Db, ref index, progress);
                    CreateTable <GXAmiUserGroupDeviceProfile>(Db, ref index, progress);
                    CreateTable <GXAmiDataCollector>(Db, ref index, progress);
                    CreateTable <GXAmiDataCollectorUserGroup>(Db, ref index, progress);
                    CreateTable <GXAmiTask>(Db, ref index, progress);
                    CreateTable <GXAmiTaskLog>(Db, ref index, progress);
                    CreateTable <GXAmiSystemError>(Db, ref index, progress);
                    CreateTable <GXAmiDeviceError>(Db, ref index, progress);
                    CreateTable <GXAmiUserActionLog>(Db, ref index, progress);
                    CreateTable <GXAmiDeviceProfilesDataBlock>(Db, ref index, progress);
                    CreateTable <GXAmiLatestValue>(Db, ref index, progress);
                    CreateTable <GXAmiValueLog>(Db, ref index, progress);
                    CreateTable <GXAmiSchedule>(Db, ref index, progress);
                    CreateTable <GXAmiScheduleTarget>(Db, ref index, progress);
                    CreateTable <GXAmiDataCollectorParameter>(Db, ref index, progress);
                    CreateTable <GXAmiDataCollectorError>(Db, ref index, progress);
                    CreateTable <GXAmiTaskData>(Db, ref index, progress);
                    CreateTable <GXAmiTaskLogData>(Db, ref index, progress);
                    CreateTable <GXAmiTrace>(Db, ref index, progress);
                    CreateTable <GXAmiTraceData>(Db, ref index, progress);
                    CreateTable <GXAmiDeviceMedia>(Db, ref index, progress);
                    CreateTable <GXAmiVisualizer>(Db, ref index, progress);
                    //Do not change settings values because they are unique.
                    Db.Insert(new GXAmiSettings("DeviceID", "0"));
                    Db.Insert(new GXAmiSettings("Version", "6"));
                    if (progress != null)
                    {
                        progress(++index, 40);
                    }

                    GXAmiUserGroup ug = new GXAmiUserGroup("SuperAdmins");
                    ug.Added = DateTime.Now.ToUniversalTime();
                    GXAmiUser user = new GXAmiUser(userName, password, UserAccessRights.SuperAdmin);
                    user.Added        = DateTime.Now.ToUniversalTime();
                    user.AccessRights = UserAccessRights.SuperAdmin;
                    Db.Insert(ug);
#if !SS4
                    ug.Id = Db.GetLastInsertId();
#else
                    ug.Id = Db.LastInsertId();
#endif
                    Db.Insert(user);
#if !SS4
                    user.Id = Db.GetLastInsertId();
#else
                    user.Id = Db.LastInsertId();
#endif
                    GXAmiUserGroupUser u = new GXAmiUserGroupUser();
                    u.Added       = DateTime.Now.ToUniversalTime();
                    u.UserID      = user.Id;
                    u.UserGroupID = ug.Id;
                    Db.Insert(u);
                    if (progress != null)
                    {
                        progress(0, 0);
                    }
                }
                catch (Exception ex)
                {
                    DropTables(Db);
                    throw ex;
                }
            }
        }
        /// <summary>
        /// Is user allowed to use service.
        /// </summary>
        /// <param name="authService"></param>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
        {
            GXAmiUser user;
            OrmLiteConnectionFactory f = authService.TryResolve <IDbConnectionFactory>() as OrmLiteConnectionFactory;

            //Connection factory is null when we are configure server at first time.
            if (f == null || f.ConnectionString == null)
            {
                return(true);
            }
            try
            {
                using (IDbConnection Db = f.OpenDbConnection())
                {
                    lock (Db)
                    {
                        if (!GuruxAMI.Service.GXManagementService.IsDatabaseCreated(Db))
                        {
#if !SS4
                            string[] items = RestPath.GetPathPartsForMatching(authService.RequestContext.PathInfo);
#else
                            string[] items = RestPath.GetPathPartsForMatching(authService.Request.PathInfo);
#endif
                            string target = items[items.Length - 1];
                            if (string.Compare(target, typeof(GXIsDatabaseCreatedRequest).Name, true) == 0 ||
                                string.Compare(target, typeof(GXCreateTablesRequest).Name, true) == 0 ||
                                string.Compare(target, typeof(GXDropTablesRequest).Name, true) == 0)
                            {
                                user    = new GXAmiUser("gurux", "gurux", UserAccessRights.SuperAdmin);
                                user.Id = 1;
                                InitUser(authService, user);
                                return(true);
                            }
                            return(false);
                        }
                        List <GXAmiUser> users = Db.Select <GXAmiUser>(q => q.Name == userName && q.Password == password);
                        if (users.Count != 1)
                        {
                            //If known DC try to get new tasks, add new task, mark task claimed or add device exception.
                            Guid guid;
#if !SS4
                            string[] items = RestPath.GetPathPartsForMatching(authService.RequestContext.PathInfo);
#else
                            string[] items = RestPath.GetPathPartsForMatching(authService.Request.PathInfo);
#endif
                            string target = items[items.Length - 1];
                            if (items != null && items.Length != 0)
                            {
                                if (string.Compare(target, typeof(GXEventsRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXEventsRegisterRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXEventsUnregisterRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXTaskDeleteRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXTasksRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXTaskUpdateRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXTasksClaimRequest).Name, true) == 0 ||
                                    string.Compare(target, typeof(GXTraceLevelRequest).Name, true) == 0)
                                {
                                    //If DC register first time and starts to listen events.
                                    if (IsGuid(userName, out guid))
                                    {
                                        //If known DC wants to listen events.
                                        List <GXAmiDataCollector> list = Db.Select <GXAmiDataCollector>(p => p.Guid == guid);
                                        if (list.Count == 1)
                                        {
                                            IAuthSession s = authService.GetSession(false);
                                            s.Id              = userName;
                                            s.UserAuthId      = Guid.NewGuid().ToString();
                                            s.UserName        = userName;
                                            s.IsAuthenticated = true;
                                            s.Roles           = new List <string>();
                                            s.Roles.Add("0");
                                            return(true);
                                        }
                                        return(false);
                                    }
                                    return(false);
                                }
                                else if (string.Compare(target, typeof(GXDataCollectorUpdateRequest).Name, true) == 0 &&
                                         IsGuid(userName, out guid))
                                {
                                    if (guid == Guid.Empty)
                                    {
                                        /* TODO:
                                         * IAuthSession s = authService.GetSession(false);
                                         * s.Id = userName;
                                         * s.UserAuthId = Guid.NewGuid().ToString();
                                         * s.UserName = userName;
                                         * s.IsAuthenticated = true;
                                         * s.Roles = new List<string>();
                                         * s.Roles.Add("0");
                                         * */
                                        return(true);
                                    }
                                    //If DC updates itself.
                                    List <GXAmiDataCollector> list = Db.Select <GXAmiDataCollector>(p => p.Guid == guid);
                                    if (list.Count == 1)
                                    {
                                        IAuthSession s = authService.GetSession(false);
                                        s.Id              = userName;
                                        s.UserAuthId      = Guid.NewGuid().ToString();
                                        s.UserName        = userName;
                                        s.IsAuthenticated = true;
                                        s.Roles           = new List <string>();
                                        s.Roles.Add("0");
                                        return(true);
                                    }
                                    return(false);
                                }
                                //If data collector wants to get data from itself by Guid.
                                else if (string.Compare(target, typeof(GXDataCollectorsRequest).Name, true) == 0 &&
                                         IsGuid(userName, out guid))
                                {
                                    List <GXAmiDataCollector> list = Db.Select <GXAmiDataCollector>(p => p.Guid == guid);
                                    if (list.Count == 1)
                                    {
                                        IAuthSession s = authService.GetSession(false);
                                        s.Id              = userName;
                                        s.UserAuthId      = Guid.NewGuid().ToString();
                                        s.UserName        = userName;
                                        s.IsAuthenticated = true;
                                        s.Roles           = new List <string>();
                                        s.Roles.Add("0");
                                        return(true);
                                    }
                                    return(false);
                                }
                                return(false);
                            }
                        }
                        user = users[0];
                        InitUser(authService, user);
                    }
                }
            }
            catch (Exception ex)
            {
                GuruxAMI.Server.AppHost.ReportError(ex);
                try
                {
                    if (!System.Diagnostics.EventLog.SourceExists("GuruxAMI"))
                    {
                        System.Diagnostics.EventLog.CreateEventSource("GuruxAMI", "Application");
                    }
                    System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
                    appLog.Source = "GuruxAMI";
                    appLog.WriteEntry(ex.Message);
                }
                catch (System.Security.SecurityException)
                {
                    //Security exception is thrown if GuruxAMI source is not exists and it's try to create without administrator privilege.
                    //Just skip this, but errors are not write to eventlog.
                }
                throw ex;
            }
            return(true);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Start GuruxAMI Data collector as console.
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //Update previous installed settings.
            if (Properties.Settings.Default.UpdateSettings)
            {
                Properties.Settings.Default.Upgrade();
                Properties.Settings.Default.UpdateSettings = false;
                Properties.Settings.Default.Save();
            }
            bool trace = false;
            GXAmiDataCollectorServer collector = null;

            try
            {
                for (int pos = 0; pos != args.Length; ++pos)
                {
                    string tag = args[pos];
                    if (tag[0] == '/' || tag[0] == '-')
                    {
                        tag = tag.Substring(1).ToLower();
                        if (tag == "h")
                        {
                            GuruxAMI.DataCollector.Properties.Settings.Default.AmiHostName = args[++pos];
                        }
                        if (tag == "p")
                        {
                            GuruxAMI.DataCollector.Properties.Settings.Default.AmiHostPort = args[++pos];
                        }
                        //Register Data Collector again.
                        if (tag == "r")
                        {
                            GuruxAMI.DataCollector.Properties.Settings.Default.AmiDCGuid = Guid.Empty;
                        }
                        //Trace messages
                        if (tag == "t")
                        {
                            trace = true;
                        }
                    }
                }

                string host = GuruxAMI.DataCollector.Properties.Settings.Default.AmiHostName;
                if (string.IsNullOrEmpty(host))
                {
                    ShowHelp();
                    return;
                }
                Guid guid = GuruxAMI.DataCollector.Properties.Settings.Default.AmiDCGuid;
                Console.WriteLine("Starting Data Collector...");
                if (!host.StartsWith("http://"))
                {
                    host = "http://" + host + ":" + GuruxAMI.DataCollector.Properties.Settings.Default.AmiHostPort + "/";
                }
                Console.WriteLine("Connecting " + host);
                GXAmiUser user = null;
                string    r, dcName = null;
                GuruxAMI.Client.GXAmiClient cl = null;
                if (guid == Guid.Empty)
                {
                    Console.WriteLine("Registering Data Collector to GuruxAMI Service: ");
                    int pos = 0;
                    do
                    {
                        Console.WriteLine("Enter user name:");
                        string username = Console.ReadLine();
                        if (username == "")
                        {
                            return;
                        }
                        Console.WriteLine("Enter password:"******"")
                        {
                            return;
                        }
                        cl = new GXAmiClient(host, username, password);
                        //Get info from registered user.
                        try
                        {
                            user = cl.GetUserInfo();
                            break;
                        }
                        catch (UnauthorizedAccessException)
                        {
                            continue;
                        }
                    }while(++pos != 3);
                    //If authorisation failed.
                    if (user == null)
                    {
                        return;
                    }
                    Console.WriteLine("Finding data collectors.");
                    GXAmiDataCollector[] dcs = cl.GetDataCollectors();
                    //If there are existing DCs...
                    if (dcs.Length != 0)
                    {
                        Console.WriteLine("Do you want to register new data collector or bind old? (n/b)");
                        do
                        {
                            r = Console.ReadLine().Trim().ToLower();
                            if (r == "n" || r == "b")
                            {
                                break;
                            }
                        }while (r == "");
                    }
                    else
                    {
                        r = "n";
                    }
                    //Old DC replaced.
                    if (r == "b")
                    {
                        Console.WriteLine("Select data collector number that you want to bind:");
                        pos = 0;
                        foreach (GXAmiDataCollector it in dcs)
                        {
                            ++pos;
                            Console.WriteLine(pos.ToString() + ". " + it.Name);
                        }
                        do
                        {
                            r = Console.ReadLine().Trim();
                            int sel = 0;
                            if (int.TryParse(r, out sel) && sel > 0 && sel <= pos)
                            {
                                guid = dcs[sel - 1].Guid;
                                break;
                            }
                        }while (true);
                    }
                    else
                    {
                        do
                        {
                            Console.WriteLine("Enter name of the data collector:");
                            dcName = Console.ReadLine().Trim();
                            if (dcName == "")
                            {
                                return;
                            }
                            if (cl.Search(new string[] { dcName }, ActionTargets.DataCollector, SearchType.Name).Length == 0)
                            {
                                GXAmiDataCollector tmp = new GXAmiDataCollector(dcName, "", "");
                                cl.AddDataCollector(tmp, cl.GetUserGroups(false));
                                guid = tmp.Guid;
                                break;
                            }
                            Console.WriteLine("Name exists. Give new one.");
                        }while (true);
                    }
                }
                collector = new GXAmiDataCollectorServer(host, guid);
                if (trace)
                {
                    collector.OnTasksAdded   += new TasksAddedEventHandler(OnTasksAdded);
                    collector.OnTasksClaimed += new TasksClaimedEventHandler(OnTasksClaimed);
                    collector.OnTasksRemoved += new TasksRemovedEventHandler(OnTasksRemoved);
                    collector.OnError        += new ErrorEventHandler(OnError);
                }
                collector.OnAvailableSerialPorts += new AvailableSerialPortsEventHandler(OnAvailableSerialPorts);
                GXAmiDataCollector dc          = collector.Init(dcName);
                //If new Data collector is added bind it to the user groups.
                if (guid == Guid.Empty && cl != null)
                {
                    cl.AddDataCollector(dc, cl.GetUserGroups(false));
                }
                if (dc != null)
                {
                    GuruxAMI.DataCollector.Properties.Settings.Default.AmiDCGuid = dc.Guid;
                }
                Console.WriteLine(string.Format("Data Collector '{0}' started.", dc.Name));
                GuruxAMI.DataCollector.Properties.Settings.Default.Save();
            }
            catch (Exception ex)
            {
                if (ex is UnauthorizedAccessException)
                {
                    Console.WriteLine("Unknown data collector.");
                    GuruxAMI.DataCollector.Properties.Settings.Default.AmiDCGuid = Guid.Empty;
                    GuruxAMI.DataCollector.Properties.Settings.Default.Save();
                }
                else
                {
                    Console.WriteLine(ex.Message);
                }
            }
            //Wait until user press enter.
            ConsoleKeyInfo key;

            while ((key = System.Console.ReadKey()).Key != ConsoleKey.Enter)
            {
                System.Console.Write("\b \b");
            }
            if (collector != null)
            {
                collector.Dispose();
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Add or update new user.
        /// </summary>
        public GXUserUpdateResponse Put(GXUserUpdateRequest request)
        {
            List <GXEventsItem> events = new List <GXEventsItem>();
            IAuthSession        s      = this.GetSession(false);
            bool edit       = GuruxAMI.Server.GXBasicAuthProvider.CanUserEdit(s);
            bool superAdmin = GuruxAMI.Server.GXBasicAuthProvider.IsSuperAdmin(s);
            long adderId    = Convert.ToInt64(s.Id);

            lock (Db)
            {
                using (var trans = Db.OpenTransaction(IsolationLevel.ReadCommitted))
                {
                    //Add new users
                    foreach (GXAmiUser it in request.Users)
                    {
                        if (string.IsNullOrEmpty(it.Name))
                        {
                            throw new ArgumentException("Invalid name.");
                        }
                        //If new user
                        if (it.Id == 0)
                        {
                            //User can't add new users.
                            if (!edit)
                            {
                                throw new ArgumentException("Access denied.");
                            }
                            if (!superAdmin && (it.AccessRights & UserAccessRights.SuperAdmin) == UserAccessRights.SuperAdmin)
                            {
                                throw new ArgumentException("Only super admin can add new super admin.");
                            }
                            if (string.IsNullOrEmpty(it.Password))
                            {
                                throw new ArgumentException("Invalid Password.");
                            }
                            it.Added = DateTime.Now.ToUniversalTime();
                            Db.Insert(it);
#if !SS4
                            it.Id = Db.GetLastInsertId();
#else
                            it.Id = Db.LastInsertId();
#endif
                            events.Add(new GXEventsItem(ActionTargets.User, Actions.Add, it));
                        }
                        else //Update user data.
                        {
                            //User can only edit itself.
                            if (!edit && adderId != it.Id)
                            {
                                throw new ArgumentException("Access denied.");
                            }
                            if (!superAdmin)
                            {
                                //User can't update user data if he do not have access to the user group.
                                long[] groups1 = GXUserGroupService.GetUserGroups(Db, adderId);
                                long[] groups2 = GXUserGroupService.GetUserGroups(Db, it.Id);
                                bool   found   = false;
                                foreach (long it1 in groups1)
                                {
                                    foreach (long it2 in groups2)
                                    {
                                        if (it1 == it2)
                                        {
                                            found = true;
                                            break;
                                        }
                                    }
                                    if (found)
                                    {
                                        break;
                                    }
                                }
                                if (!found)
                                {
                                    throw new ArgumentException("Access denied.");
                                }
                            }
                            //Get Added time.
#if !SS4
                            GXAmiUser orig = Db.GetById <GXAmiUser>(it.Id);
#else
                            GXAmiUser orig = Db.SingleById <GXAmiUser>(it.Id);
#endif
                            it.Added = orig.Added;
                            if (string.IsNullOrEmpty(it.Password))
                            {
                                it.Password = orig.Password;
                            }
                            Db.Update(it);
                            events.Add(new GXEventsItem(ActionTargets.User, Actions.Edit, it));
                        }
                    }
                    trans.Commit();
                }
            }
            AppHost host = this.ResolveService <AppHost>();
            host.SetEvents(Db, this.Request, adderId, events);
            return(new GXUserUpdateResponse(request.Users));
        }
Exemplo n.º 10
0
        /// <summary>
        /// Delete selected user.
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public GXUserDeleteResponse Post(GXUserDeleteRequest request)
        {
            IAuthSession s  = this.GetSession(false);
            int          id = Convert.ToInt32(s.Id);

            if (id == 0)
            {
                throw new ArgumentException("Remove failed. Invalid session ID.");
            }
            if (!GuruxAMI.Server.GXBasicAuthProvider.CanUserEdit(s))
            {
                throw new ArgumentException("Remove not allowed.");
            }
            List <GXEventsItem> events = new List <GXEventsItem>();
            bool superAdmin            = GuruxAMI.Server.GXBasicAuthProvider.IsSuperAdmin(s);

            lock (Db)
            {
                foreach (int it in request.UserIDs)
                {
                    if (it == 0)
                    {
                        throw new ArgumentException("ID is required");
                    }
                    if (!superAdmin && !GXUserGroupService.CanAccess(Db, id, it))
                    {
                        throw new ArgumentException("Access denied.");
                    }
#if !SS4
                    GXAmiUser user = Db.QueryById <GXAmiUser>(it);
#else
                    GXAmiUser user = Db.SingleById <GXAmiUser>(it);
#endif
                    //Remove user from the user group.
                    if (request.GroupIDs != null && request.GroupIDs.Length != 0)
                    {
                        foreach (long gid in request.GroupIDs)
                        {
                            if (!superAdmin)
                            {
                                List <GXAmiUser> list = GetUsers(s, Db, 0, gid, false, false, null, SearchOperator.None, SearchType.All);
                                if (list.Count == 1)
                                {
                                    throw new ArgumentException("Remove not allowed.");
                                }
                            }
                            string             query = string.Format("UserGroupID = {0} AND UserID = {1}", gid, it);
                            GXAmiUserGroupUser item  = Db.Select <GXAmiUserGroupUser>(query)[0];
                            Db.Delete <GXAmiUserGroupUser>(item);
#if !SS4
                            GXAmiUserGroup ug = Db.QueryById <GXAmiUserGroup>(gid);
#else
                            GXAmiUserGroup ug = Db.SingleById <GXAmiUserGroup>(gid);
#endif
                            events.Add(new GXEventsItem(ActionTargets.User, Actions.Edit, user));
                            events.Add(new GXEventsItem(ActionTargets.User, Actions.Edit, ug));
                        }
                    }
                    else //Remove user.
                    {
                        // You can not delete yourself.
                        if (it == id)
                        {
                            throw new ArgumentException("Remove not allowed.");
                        }
                        if (request.Permanently)
                        {
                            Db.DeleteById <GXAmiUser>(it);
                        }
                        else
                        {
                            user.Removed = DateTime.Now.ToUniversalTime();
                            Db.UpdateOnly(user, p => p.Removed, p => p.Id == it);
                        }
                        events.Add(new GXEventsItem(ActionTargets.User, Actions.Remove, user));
                        //Remove all user groups of the user.
                        long[] list = GXUserGroupService.GetUserGroups(Db, it);

                        //TODO: Remove only if last user.
                        foreach (long gid in list)
                        {
#if !SS4
                            GXAmiUserGroup ug = Db.QueryById <GXAmiUserGroup>(gid);
#else
                            GXAmiUserGroup ug = Db.SingleById <GXAmiUserGroup>(gid);
#endif
                            if (request.Permanently)
                            {
                                Db.DeleteById <GXAmiUserGroup>(gid);
                            }
                            else
                            {
                                ug.Removed = DateTime.Now.ToUniversalTime();
                                Db.UpdateOnly(ug, p => p.Removed, p => p.Id == gid);
                            }
                            events.Add(new GXEventsItem(ActionTargets.User, Actions.Edit, user));
                            events.Add(new GXEventsItem(ActionTargets.User, Actions.Edit, ug));
                        }
                    }
                }
            }
            AppHost host = this.ResolveService <AppHost>();
            host.SetEvents(Db, this.Request, id, events);
            return(new GXUserDeleteResponse());
        }