Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C and OS user type

Is there any way to get currently logged in user type (root, admin or normal) through objective C?

I know about NSFullUserName() which gives user name, but how to retrieve user type?

Thanks.

like image 918
Swapnil Avatar asked Dec 16 '22 12:12

Swapnil


1 Answers

You can retrieve the user group using getpwnam or getpwuid then use getgrgid to get the group name from the gid.

These are C functions in the standard library.

-- EDIT: Here is a short, poorly coded C example ---

Here is a small example, on mac os in the terminal it should build using make (if you name the file getpwnam_example.c you can do $ make getpwnam_example in the same directory as the c file).

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <strings.h>
#include <pwd.h>
#include <grp.h>

int main(int argc, char **argv) {

    uid_t current_user_id = getuid();
    printf("My Current UID is %d\n", current_user_id);

    struct passwd *pwentry = getpwuid(current_user_id);
    printf("My Current Name is %s\n", pwentry->pw_gecos);
    printf("My Current Group ID is %d\n", pwentry->pw_gid);

    struct group *grentry = getgrgid(getgid());
    printf("My Current Group Name is %s\n", grentry->gr_name);

    printf("Am I an admin? ");
    struct group *admin_group = getgrnam("admin");
    while(*admin_group->gr_mem != NULL) {
        if (strcmp(pwentry->pw_name, *admin_group->gr_mem) == 0) {
            printf("yes!\n");
        }
        admin_group->gr_mem++;
    }

    return 0;
}
like image 173
Joshua Smith Avatar answered Jan 02 '23 16:01

Joshua Smith