package auth

import (
    "errors"
    "fmt"
    "log"
    "net/url"
    "regexp"
    "time"

    "github.com/nsqio/nsq/internal/http_api"
)

type Authorization struct {
    Topic       string   `json:"topic"`
    Channels    []string `json:"channels"`
    Permissions []string `json:"permissions"`
}

type State struct {
    TTL            int             `json:"ttl"`
    Authorizations []Authorization `json:"authorizations"`
    Identity       string          `json:"identity"`
    IdentityURL    string          `json:"identity_url"`
    Expires        time.Time
}

func (a *Authorization) HasPermission(permission string) bool {
    for _, p := range a.Permissions {
        if permission == p {
            return true
        }
    }
    return false
}

func (a *Authorization) IsAllowed(topic, channel string) bool {
    if channel != "" {
        if !a.HasPermission("subscribe") {
            return false
        }
    } else {
        if !a.HasPermission("publish") {
            return false
        }
    }

    topicRegex := regexp.MustCompile(a.Topic)

    if !topicRegex.MatchString(topic) {
        return false
    }

    for _, c := range a.Channels {
        channelRegex := regexp.MustCompile(c)
        if channelRegex.MatchString(channel) {
            return true
        }
    }
    return false
}

func (a *State) IsAllowed(topic, channel string) bool {
    for _, aa := range a.Authorizations {
        if aa.IsAllowed(topic, channel) {
            return true
        }
    }
    return false
}

func (a *State) IsExpired() bool {
    if a.Expires.Before(time.Now()) {
        return true
    }
    return false
}

func QueryAnyAuthd(authd []string, remoteIP, tlsEnabled, authSecret string,
    connectTimeout time.Duration, requestTimeout time.Duration) (*State, error) {
    for _, a := range authd {
        authState, err := QueryAuthd(a, remoteIP, tlsEnabled, authSecret, connectTimeout, requestTimeout)
        if err != nil {
            log.Printf("Error: failed auth against %s %s", a, err)
            continue
        }
        return authState, nil
    }
    return nil, errors.New("Unable to access auth server")
}

func QueryAuthd(authd, remoteIP, tlsEnabled, authSecret string,
    connectTimeout time.Duration, requestTimeout time.Duration) (*State, error) {
    v := url.Values{}
    v.Set("remote_ip", remoteIP)
    v.Set("tls", tlsEnabled)
    v.Set("secret", authSecret)

    endpoint := fmt.Sprintf("http://%s/auth?%s", authd, v.Encode())

    var authState State
    client := http_api.NewClient(nil, connectTimeout, requestTimeout)
    if err := client.GETV1(endpoint, &authState); err != nil {
        return nil, err
    }

    // validation on response
    for _, auth := range authState.Authorizations {
        for _, p := range auth.Permissions {
            switch p {
            case "subscribe", "publish":
            default:
                return nil, fmt.Errorf("unknown permission %s", p)
            }
        }

        if _, err := regexp.Compile(auth.Topic); err != nil {
            return nil, fmt.Errorf("unable to compile topic %q %s", auth.Topic, err)
        }

        for _, channel := range auth.Channels {
            if _, err := regexp.Compile(channel); err != nil {
                return nil, fmt.Errorf("unable to compile channel %q %s", channel, err)
            }
        }
    }

    if authState.TTL <= 0 {
        return nil, fmt.Errorf("invalid TTL %d (must be >0)", authState.TTL)
    }

    authState.Expires = time.Now().Add(time.Duration(authState.TTL) * time.Second)
    return &authState, nil
}

authorizations.go的更多相关文章

  1. WSO2 API Manager 替换mysql作为数据库,解决AuthorizationUtils Could not set authorizations for the root问题

    按照wso2官网(https://docs.wso2.com/display/ADMIN44x/Changing+to+MySQL)配置AM的数据库,想从H2换成Mysql5.7,费了将近一天的时间, ...

  2. (转载) RESTful API 设计指南

    作者: 阮一峰 日期: 2014年5月22日 网络应用程序,分为前端和后端两个部分.当前的发展趋势,就是前端设备层出不穷(手机.平板.桌面电脑.其他专用设备......). 因此,必须有一种统一的机制 ...

  3. 使用swagger作为restful api的doc文档生成

    初衷 记得以前写接口,写完后会整理一份API接口文档,而文档的格式如果没有具体要求的话,最终展示的文档则完全决定于开发者的心情.也许多点,也许少点.甚至,接口总是需要适应新需求的,修改了,增加了,这份 ...

  4. .NET WebAPI 用ActionFilterAttribute实现token令牌验证与对Action的权限控制

    项目背景是一个社区类的APP(求轻吐...),博主主要负责后台业务及接口.以前没玩过webAPI,但是领导要求必须用这个(具体原因鬼知道),只好硬着头皮上了. 最近刚做完权限这一块,分享出来给大家.欢 ...

  5. RESTful API 设计指南

    转自:http://www.ruanyifeng.com/blog/2014/05/restful_api.html 网络应用程序,分为前端和后端两个部分.当前的发展趋势,就是前端设备层出不穷(手机. ...

  6. RESTful API URI 设计的一些总结

    非常赞的四篇文章: Resource Naming Best Practices for Designing a Pragmatic RESTful API 撰写合格的 REST API JSON 风 ...

  7. PHP7函数大全(4553个函数)

    转载来自: http://www.infocool.net/kb/PHP/201607/168683.html a 函数 说明 abs 绝对值 acos 反余弦 acosh 反双曲余弦 addcsla ...

  8. CentOS搭建SVN记录

    1.安装subversion(client and server) $ yum install subversion $ yum install mod_dav_svn 安装成功之后使用 svnser ...

  9. geotrellis使用(五)使用scala操作Accumulo

    要想搞明白Geotrellis的数据处理情况,首先要弄清楚数据的存放,Geotrellis将数据存放在Accumulo中. Accumulo是一个分布式的Key Value型NOSQL数据库,官网为( ...

随机推荐

  1. ubuntu下无法编译ruby-2.1.5提示something wrong with CFLAGS -arch x86_64

    在Mac OS X10.10下以下语句运行没有问题: ./configure -prefix=/Users/apple/src/ruby_src/ruby2.1.5_installed --with- ...

  2. 基于condition 实现的线程安全的优先队列(python实现)

    可以把Condiftion理解为一把高级的琐,它提供了比Lock, RLock更高级的功能,允许我们能够控制复杂的线程同步问题.threadiong.Condition在内部维护一个琐对象(默认是RL ...

  3. ambari2.6.1汉化记录

    1.1测试机 Apache hadoop2.6Apache ambari 2.6.1集群规模:单节点操作系统 CentOS7以下所有操作均在root用户下执行 1.2安装环境 安装Maventar - ...

  4. VirtualBox 自动挂载共享文件夹

    在文件 /etc/rc.local 中(用root用户)追加如下命令 mount -t vboxsf sharing /mnt/share 重启后就大功告成了,网上大部分说的修改etc下面的fstab ...

  5. sql server求分组最大值,最小值,最大值对应时间,和最小值对应时间

    先创建数据库 CREATE TABLE [dbo].[Students]( [Id] [int] IDENTITY(1,1) NOT NULL, [age] [int] NULL, [name] [n ...

  6. Mybatis 系列6

    上篇系列5中 简单看了一下TypeHandler, 本次将结束对于mybatis的配置文件的学习, 本次涉及到剩下没提及到的几个节点的配置:objectFactory.databaseIdProvid ...

  7. Python HTTP库requests中文页面乱码解决方案!

    http://www.cnblogs.com/bitpeng/p/4748872.html Python中文乱码,是一个很大的坑,自己不知道在这里遇到多少问题了.还好通过自己不断的总结,现在遇到乱码的 ...

  8. memcached server install(WSL)

    prepare:0) libevent-dev1) libseccomp-dev2) build-essential3) automake install: https://www.liquidweb ...

  9. 提高Maven下载jar包的速度

    1.提高Maven下载jar包的速度 打开项目所配置的maven包下conf目录下的settings.xml 找到  <mirrors>标签添加一下内容: 1 <!-- 阿里云仓库 ...

  10. (function($){...})(jQuery) 含义 【转】

    经常用,今天总结一下,下文摘自某网友的总结: (function($){...})(jQuery)实际上是匿名函数,不懂得朋友可以继续往下看. 这里实际上是匿名函数 function(arg){... ...