Hack to determine if file has write permissions for current user Avoids having to check user, group, etc, but it's probably slow.
14102
function isWriteable(file) {
  let writePermission = true;
  try {
    const __fd = fs.openSync(file, 'a');
    fs.closeSync(__fd);
  } catch (e) {
    /* istanbul ignore next */
    writePermission = false;
  }

  return writePermission;
}
464883
def can_write(self):
        
        sm = getSecurityManager()
        permission = permissions.ModifyPortalContent

        if not sm.checkPermission(permission, self.context):
            return False
        return True
157785
def has_access(f):
    
    if hasattr(f, '_permission_name'):
        permission_str = f._permission_name
    else:
        permission_str = f.__name__

    def wraps(self, *args, **kwargs):
        permission_str = PERMISSION_PREFIX + f._permission_name
        if self.appbuilder.sm.has_access(
                permission_str,
                self.__class__.__name__
        ):
            return f(self, *args, **kwargs)
        else:
            log.warning(
                LOGMSG_ERR_SEC_ACCESS_DENIED.format(
                    permission_str,
                    self.__class__.__name__
                )
            )
            flash(as_unicode(FLAMSG_ERR_SEC_ACCESS_DENIED), "danger")
        return redirect(
            url_for(
                self.appbuilder.sm.auth_view.__class__.__name__ + ".login",
                next=request.url
            )
        )
    f._permission_name = permission_str
    return functools.update_wrapper(wraps, f)
905475
def check_file(filepath):
    '''
        
    '''
    check_path(filepath)
    if not os.path.exists(filepath):
        print("WARNING: File does not exist. Creating it: %s" % filepath)
        open(filepath, 'a').close()
    try:
        print("Setting access rights for %s for www-data user" % (filepath))
        uid = pwd.getpwnam("www-data").pw_uid
        gid = grp.getgrnam("www-data").gr_gid
        os.chown(filepath, uid, gid)
        os.chmod(filepath, 0o660)  # rw-rw---
    except Exception:
        print("WARNING: Could not adjust file system permissions for %s. Make sure your web server can write into it." % filepath)
1272810
def fix_permissions (self):
        """"""
        if os.name == 'posix' and not self.dry_run:
            # Make the data files we just installed world-readable,
            # and the directories world-executable as well.
            for path in self.get_outputs():
                mode = os.stat(path)[stat.ST_MODE]
                if stat.S_ISDIR(mode):
                    mode |= 0o11
                mode |= 0o44
                os.chmod(path, mode)
1039177
private function checkFilePermissions(\SplFileInfo $fileInfo): bool {
    // Others.
    $perms = $fileInfo->getPerms();
    if ($perms & 0001) return true;

    // Group.
    $gid = function_exists('posix_getgid') ? posix_getgid() : -1;
    if ($perms & 0010) return $gid == $fileInfo->getGroup();

    // Owner.
    $uid = function_exists('posix_getuid') ? posix_getuid() : -1;
    if ($perms & 0100) return $uid == $fileInfo->getOwner();

    // Root.
    return $perms & (0100 | 0010) ? $uid == 0 : false;
  }
926005
def allow_rwe(self, name):
        """"""
        assert name in PERMISSIONS.keys()
        os.chmod(self.file_path, PERMISSIONS[name]['all'])
317087
def _permission_trees(permissions):
        """"""
        treecache = PermissionTreeCache()
        cached = treecache.get()
        if not cached:
            tree = PermissionTreeBuilder()
            for permission in permissions:
                tree.insert(permission)
            result = tree.serialize()
            treecache.set(result)
            return result
        return cached
847244
public function check_permissions() {
        if ($this->recordid) {
            if (data_isowner($this->recordid)) {
                return has_capability('mod/data:exportownentry', context_module::instance($this->cm->id));
            }
            return has_capability('mod/data:exportentry', context_module::instance($this->cm->id));
        }
        if ($this->has_export_config() && !$this->get_export_config('mineonly')) {
            return has_capability('mod/data:exportallentries', context_module::instance($this->cm->id));
        }
        return has_capability('mod/data:exportownentry', context_module::instance($this->cm->id));
    }
958768
final public static function checkPermission()
    {
        $base =  __DIR__."/../../";
        if (!self::checkIsExecutable($base."elements/") ||
            !self::checkIsReadable($base."elements/") || !self::checkIsWritable($base."elements/")) {
            return (json_encode(array("code" => 500, "results" => "NOK", "wr" => "elements", "msg" =>
                "Folder elements/ does not have correct permission. Must be read, write, executable permission")));
        }

        if (!self::checkIsExecutable($base."apps/") || !self::checkIsReadable($base."apps/") ||
            !self::checkIsWritable($base."apps/")) {
            return (json_encode(array("code" => 500, "results" => "NOK", "wr" => "apps/", "msg" =>
                "Folder apps/ does not have correct permission. Must be read, write, executable permission")));
        }

        if (!self::checkIsExecutable($base."vendor/") || !self::checkIsReadable($base."vendor/") ||
            !self::checkIsWritable($base."vendor/")) {
            return (json_encode(array("code" => 500, "results" => "NOK", "wr" => "vendor/", "msg" =>
                "Folder vendor/ does not have correct permission. Must be read, write, executable permission")));
        }

        if (!self::checkIsExecutable($base."public/components/libs") ||
            !self::checkIsReadable($base."public/components/libs") ||
            !self::checkIsWritable($base."public/components/libs")) {
            return (json_encode(array("code" => 500, "results" => "NOK", "wr" => "public/components/libs/", "msg" =>
                "Folder public/components/libs/ does not have correct permission. 
                Must be read, write, executable permissions")));
        }

        return (json_encode(array("code" => 200, "results" => "OK")));
    }
439961
static ZTFilePermissions fromPosixFileMode(int mode) {
    ZTFilePermissions permissions = new ZTFilePermissions();
    
    permissions.setOwnerCanExecute( (mode &  OWNER_EXECUTE_FLAG)  > 0 );
    permissions.setGroupCanExecute( (mode &  GROUP_EXECUTE_FLAG)  > 0 );
    permissions.setOthersCanExecute((mode &  OTHERS_EXECUTE_FLAG) > 0 );
    
    permissions.setOwnerCanWrite( (mode &  OWNER_WRITE_FLAG)  > 0 );
    permissions.setGroupCanWrite( (mode &  GROUP_WRITE_FLAG)  > 0 );
    permissions.setOthersCanWrite((mode &  OTHERS_WRITE_FLAG) > 0 );
    
    permissions.setOwnerCanRead( (mode &  OWNER_READ_FLAG)  > 0 );
    permissions.setGroupCanRead( (mode &  GROUP_READ_FLAG)  > 0 );
    permissions.setOthersCanRead((mode &  OTHERS_READ_FLAG) > 0 );
    
    return permissions;
  }
1369236
def has_permission(cls, user):
        
        # no login is needed, so its always fine
        if not cls.requires_login:
            return True

        # if user is somehow not logged in
        if not user.is_authenticated:
            return False

        # attribute permission_required is mandatory, returns tuple
        perms = cls.get_permission_required()
        # if perms are defined and empty, we skip checking
        if not perms:
            return True

        # get role of user, skip admin role
        role = user.urole.role.name
        if role == cls.ADMIN:
            return True

        # check if at least one permissions is valid
        for permission in perms:
            if cls.check_permission(role, permission):
                return True

        # permission denied
        return False
523561
def check_auth(self):
        """"""
        # access permissions
        if self.auth is not None:
            return self.auth(self.request)

        return self.public_readble, self.public_writable
1124631
def verify_files(files, user):
    '''
    
    '''
    if salt.utils.platform.is_windows():
        return True
    import pwd  # after confirming not running Windows
    try:
        pwnam = pwd.getpwnam(user)
        uid = pwnam[2]
    except KeyError:
        err = ('Failed to prepare the Salt environment for user '
               '{0}. The user is not available.\n').format(user)
        sys.stderr.write(err)
        sys.exit(salt.defaults.exitcodes.EX_NOUSER)

    for fn_ in files:
        dirname = os.path.dirname(fn_)
        try:
            if dirname:
                try:
                    os.makedirs(dirname)
                except OSError as err:
                    if err.errno != errno.EEXIST:
                        raise
            if not os.path.isfile(fn_):
                with salt.utils.files.fopen(fn_, 'w'):
                    pass

        except IOError as err:
            if os.path.isfile(dirname):
                msg = 'Failed to create path {0}, is {1} a file?'.format(fn_, dirname)
                raise SaltSystemExit(msg=msg)
            if err.errno != errno.EACCES:
                raise
            msg = 'No permissions to access "{0}", are you running as the correct user?'.format(fn_)
            raise SaltSystemExit(msg=msg)

        except OSError as err:
            msg = 'Failed to create path "{0}" - {1}'.format(fn_, err)
            raise SaltSystemExit(msg=msg)

        stats = os.stat(fn_)
        if uid != stats.st_uid:
            try:
                os.chown(fn_, uid, -1)
            except OSError:
                pass
    return True
165801
def download_permissions
        can :download, String do |id|
          test_download(id)
        end

        can :download, SolrDocument do |obj|
          cache.put(obj.id, obj)
          test_download(obj.id)
        end
      end
663864
def check_perms(perms, user, slug, raise_exception=False):
    """"""
    if isinstance(perms, string_types):
        perms = {perms}
    else:
        perms = set(perms)

    allowed_users = ACLRule.get_users_for(perms, slug)

    if allowed_users:
        return user in allowed_users

    if perms.issubset(set(WALIKI_ANONYMOUS_USER_PERMISSIONS)):
        return True

    if is_authenticated(user) and perms.issubset(set(WALIKI_LOGGED_USER_PERMISSIONS)):
        return True

    # First check if the user has the permission (even anon users)
    if user.has_perms(['waliki.%s' % p for p in perms]):
        return True
    # In case the 403 handler should be called raise the exception
    if raise_exception:
        raise PermissionDenied
    # As the last resort, show the login form
    return False
984114
def _check_permission(self, request):
        

        if self.access_controller:
            self.access_controller.check_perm(request, self)