Skip to content

Commit

Permalink
[UPD][#14] Implemented cobra command
Browse files Browse the repository at this point in the history
  • Loading branch information
Federico Maggi committed Sep 5, 2016
1 parent 87c13b1 commit 3f12900
Show file tree
Hide file tree
Showing 3 changed files with 93 additions and 44 deletions.
12 changes: 6 additions & 6 deletions 3n4chatserver/authservice.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,19 @@ type AuthRPC struct {

// NewAuthRPC creates a new instance of the RPC
// client used to interact with the auth service.
func NewAuthRPC(addr string, port int) (*AuthRpc, error) {
func NewAuthRPC(addr string, port int) (*AuthRPC, error) {
address := fmt.Sprintf("%s:%d", addr, port)
rawClient, err := rpc.DialHTTP("tcp", address)
if err != nil {
return nil, err
}
return &AuthRpc{
return &AuthRPC{
client: rawClient,
}, nil
}

// Login grant access to users, over RPC, using username and password.
func (a *AuthRpc) Login(username string, password string) ([]byte, error) {
func (a *AuthRPC) Login(username string, password string) ([]byte, error) {
// perform login on RPC service
var loginResponse auth.LoginResponseArg
err := a.client.Call("Login.Login", &auth.LoginRequestArg{
Expand All @@ -59,7 +59,7 @@ func (a *AuthRpc) Login(username string, password string) ([]byte, error) {
}

// Logout remove actual active sessions over RPC.
func (a *AuthRpc) Logout(token []byte) ([]byte, error) {
func (a *AuthRPC) Logout(token []byte) ([]byte, error) {
var logoutResponse auth.LogoutResponseArg
err := a.client.Call("Login.Logout", &auth.LogoutRequestArg{
Token: token,
Expand All @@ -72,7 +72,7 @@ func (a *AuthRpc) Logout(token []byte) ([]byte, error) {

// AuthoriseAndGetInfo if the token is valid returns info about
// the associated user over RPC service.
func (a *AuthRpc) AuthoriseAndGetInfo(token []byte) (*auth.UserInfoResponseArg, error) {
func (a *AuthRPC) AuthoriseAndGetInfo(token []byte) (*auth.UserInfoResponseArg, error) {
// verify token and retrieve user infos
var authResponse auth.UserInfoResponseArg
err := a.client.Call("SessionAuth.UserInfo", &auth.AuthenticateRequestArg{
Expand All @@ -85,6 +85,6 @@ func (a *AuthRpc) AuthoriseAndGetInfo(token []byte) (*auth.UserInfoResponseArg,
}

// Close closes RPC connection.
func (a *AuthRpc) Close() error {
func (a *AuthRPC) Close() error {
return a.client.Close()
}
58 changes: 20 additions & 38 deletions 3n4chatserver/chatservice.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ package main
// Go standard libraries
import (
"fmt"
"net/http"
// "net/http"
"os"
)

Expand All @@ -30,64 +30,46 @@ var log *logger.LogFacility
// Cobra parsed arguments
var a args

// init a cobra command
var rootCmd = &cobra.Command{
Use: "3n4chatserver",
Short: "3nigm4 chat",
Long: "Command line 3nigm4 chat server.",
RunE: func(cmd *cobra.Command, args []string) error {
printLogo(nil)
return fmt.Errorf("undefined command, select a valid one\n")
},
}

func init() {
// start up logging facility
log = logger.NewLogFacility("3n4CHAT", true, true)
// init a cobra command
rootCmd := &cobra.Command{
Use: "3n4chatserver",
Short: "a",
Long: "Command line 3nigm4 chat server.",
RunE: func(cmd *cobra.Command, args []string) error {
printLogo(nil)
return fmt.Errorf("undefined command, select a valid one\n")
},
}

// set flags
rootCmd.PersistentFlags().BoolVarP(&a.verbose, "verbose", "v", false, "enable verbose mode")
// database references
rootCmd.PersistentFlags().StringVarP(&a.dbAddresses, "dbaddrs", "d", "127.0.0.1:27017", "the database cluster addresses")
rootCmd.PersistentFlags().StringVarP(&a.dbUsername, "dbuser", "u", "", "the database user name")
rootCmd.PersistentFlags().StringVarP(&a.dbPassword, "dbpwd", "w", "", "the database password")
rootCmd.PersistentFlags().StringVarP(&a.dbAuth, "dbauth", "", "admin", "the database auth db")
// service coordinates
rootCmd.PersistentFlags().StringVarP(&a.address, "address", "a", "0.0.0.0", "the http/https listening address")
rootCmd.PersistentFlags().IntVarP(&a.port, "port", "p", 7443, "the http/https listening port")
// SSL/TLS
rootCmd.PersistentFlags().StringVarP(&a.sslCertificate, "certificate", "s", "", "the SSL/TLS certificate PEM file path")
rootCmd.PersistentFlags().StringVarP(&a.sslPrivateKey, "privatekey", "S", "", "the SSL/TLS private key PEM file path")
// auth RPC service
rootCmd.PersistentFlags().StringVarP(&a.authServiceAddress, "authaddr", "A", "", "the authorisation RPC service address")
rootCmd.PersistentFlags().IntVarP(&a.authServicePort, "authport", "P", 7931, "the authorisation RPC service port")

// parse flags
rootCmd.ParseFlags(os.Args)
}

func main() {
serviceAddress := fmt.Sprintf("%s:%d", a.address, a.port)
info := make(map[string]string)
info["bind"] = serviceAddress

// print logo
printLogo(info)
printLogo(nil)

if a.verbose {
log.MessageLog("Certificate: `%s` | Private key: `%s`\n", a.sslCertificate, a.sslPrivateKey)
}

// check for SSL/TLS certificates
if a.sslCertificate == "" || a.sslPrivateKey == "" {
log.ErrorLog("Invalid SSL/TLS certificates paths\n")
// execute command
rootCmd.AddCommand(serveCmd)
_, err := rootCmd.ExecuteC()
if err != nil {
log.CriticalLog("%s.\n", err.Error())
os.Exit(1)
}

// set up SSL/TLS
log.MessageLog("Starting SSL/TLS services on address %s.\n", serviceAddress)
err := http.ListenAndServeTLS(serviceAddress, a.sslCertificate, a.sslPrivateKey, router())
if err != nil {
log.ErrorLog("Unable to listen and serve on address %s. cause: [%s].\n", serviceAddress, err.Error())
}
os.Exit(0)
}

func printLogo(i map[string]string) {
Expand Down
67 changes: 67 additions & 0 deletions 3n4chatserver/serve_cmd.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
//
// 3nigm4 chatservice package
// Author: Federico Maggi <[email protected]>
// v1.0 23/08/2016
//
package main

// Go standard libraries
import (
"fmt"
"net/http"
"os"
)

// Third party libraries
import (
"github.com/spf13/cobra"
)

// ServeCmd start the http/https server listening
// on exec args, used to register to cobra lib root
// command.
var serveCmd = &cobra.Command{
Use: "serve",
Short: "Serve trougth http/https",
Long: "Launch http service to expose storage API services.",
Example: "3n4chatservice serve -d 127.0.0.1:27017 -u dbuser -w dbpwd -a 0.0.0.0 -p 443 -s /tmp/cert.pem -S /tmp/pvkey.pem -v",
}

func init() {
// service coordinates
serveCmd.PersistentFlags().StringVarP(&a.address, "address", "a", "0.0.0.0", "the http/https listening address")
serveCmd.PersistentFlags().IntVarP(&a.port, "port", "p", 7443, "the http/https listening port")
// SSL/TLS
serveCmd.PersistentFlags().StringVarP(&a.sslCertificate, "certificate", "s", "", "the SSL/TLS certificate PEM file path")
serveCmd.PersistentFlags().StringVarP(&a.sslPrivateKey, "privatekey", "S", "", "the SSL/TLS private key PEM file path")
// files parameters
serveCmd.RunE = serve
}

// serve command expose a RPC service that exposes all authentication
// related function to the outside.
func serve(cmd *cobra.Command, args []string) error {
cmd.ParseFlags(os.Args)
serviceAddress := fmt.Sprintf("%s:%d", a.address, a.port)
info := make(map[string]string)
info["bind"] = serviceAddress

if a.verbose {
log.MessageLog("Certificate: `%s` | Private key: `%s`\n", a.sslCertificate, a.sslPrivateKey)
}

// check for SSL/TLS certificates
if a.sslCertificate == "" || a.sslPrivateKey == "" {
log.ErrorLog("Invalid SSL/TLS certificates paths\n")
os.Exit(1)
}

// set up SSL/TLS
log.MessageLog("Starting SSL/TLS services on address %s.\n", serviceAddress)
err := http.ListenAndServeTLS(serviceAddress, a.sslCertificate, a.sslPrivateKey, router())
if err != nil {
log.ErrorLog("Unable to listen and serve on address %s. cause: [%s].\n", serviceAddress, err.Error())
}

return nil
}

0 comments on commit 3f12900

Please sign in to comment.