This commit is contained in:
sammyoina
2020-03-06 13:07:28 +03:00
parent 2bc0c1c3fc
commit 87b7d1b300
6 changed files with 543 additions and 0 deletions
BIN
View File
Binary file not shown.
+26
View File
@@ -0,0 +1,26 @@
package main
import (
"log"
"qualEATS/userPB"
"golang.org/x/net/context"
"google.golang.org/grpc"
)
func main() {
var conn *grpc.ClientConn
conn, err := grpc.Dial(":7777", grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %s", err)
}
defer conn.Close()
defer conn.Close()
c := userPB.NewAuthServiceClient(conn)
response, err := c.Signup(context.Background(), &userPB.RegDetails{Username: "Sam", Password: "qualis", Usertype: "client", Company: "Dummy", Email: "anemailaddress"})
if err != nil {
log.Fatalf("Error when calling Login: %s", err)
}
log.Printf("Response from server: %s", response.Token)
}
BIN
View File
Binary file not shown.
+170
View File
@@ -0,0 +1,170 @@
package main
import (
"context"
"fmt"
"log"
"net"
"time"
userPB "qualEATS/userPB"
"github.com/dgrijalva/jwt-go"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"google.golang.org/grpc"
)
type Users struct {
Id string `bson:"_id"`
Username string `bson:"name"`
Password string `bson:"password"`
}
type Regst struct {
Username string `bson:"name"`
Password string `bson:"password"`
Usertype string `bson:"usertype"`
Company string `bson:"company"`
Email string `bson:"email"`
}
var jwtKey = []byte("affd25090f0b173ca7ce22837167579e")
type AuthServiceServer struct {
}
type Claims struct {
Username string `json:"username"`
jwt.StandardClaims
}
func (s *AuthServiceServer) Login(ctx context.Context, req *userPB.LoginReq) (*userPB.LoginRes, error) {
uName := req.Username
pWD := req.Pwad
expirationTime := time.Now().Add(5 * time.Minute)
//fmt.Printf("%s", pWD)
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
// Check the connection
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
//fmt.Println("Connected to MongoDB!")
collection := client.Database("qualEATS").Collection("users")
var result Users
filter := bson.D{{"name", uName}}
var ntx int64 = 0
err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
ntx = 1
//log.Fatal(err)
}
//fmt.Printf("Found a single document: %+v\n", result.Password)
if ntx == 0 {
if pWD == result.Password {
claims := &Claims{
Username: uName,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err := token.SignedString(jwtKey)
if err != nil {
return &userPB.LoginRes{Token: "Internal Error"}, nil
}
return &userPB.LoginRes{Token: tokenString}, nil
} else {
return &userPB.LoginRes{Token: "Wrong password"}, nil
}
} else {
return &userPB.LoginRes{Token: "User does not exist"}, nil
}
}
func (s *AuthServiceServer) Signup(ctx context.Context, req1 *userPB.RegDetails) (*userPB.LoginRes, error) {
uName1 := req1.Username
Pwad1 := req1.Password
uType := req1.Usertype
comp := req1.Company
email := req1.Email
expirationTime := time.Now().Add(5 * time.Minute)
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
// Check the connection
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
//fmt.Println("Connected to MongoDB!")
collection := client.Database("qualEATS").Collection("users")
var result Regst
filter := bson.D{{"name", uName1}}
var ntx int64 = 0
err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
ntx = 1
//log.Fatal(err)
}
tokenString := ""
if ntx == 1 {
newUser := Regst{uName1, Pwad1, uType, comp, email}
insertResult, err := collection.InsertOne(context.TODO(), newUser)
if err != nil {
log.Fatal(err)
}
if insertResult.InsertedID != nil {
claims := &Claims{
Username: uName1,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expirationTime.Unix(),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
tokenString, err = token.SignedString(jwtKey)
} else {
tokenString = "Internal error"
}
} else {
tokenString = "Username exists"
}
return &userPB.LoginRes{Token: tokenString}, nil
}
func main() {
//ctx := context.Background()
lis, err := net.Listen("tcp", fmt.Sprintf(":%d", 7777))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := AuthServiceServer{}
grpcServer := grpc.NewServer()
userPB.RegisterAuthServiceServer(grpcServer, &s)
if err := grpcServer.Serve(lis); err != nil {
log.Fatalf("failed to serve: %s", err)
}
}
+325
View File
@@ -0,0 +1,325 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: userPB.proto
package userPB
import (
context "context"
fmt "fmt"
proto "github.com/golang/protobuf/proto"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
math "math"
)
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
type LoginReq struct {
Username string `protobuf:"bytes,1,opt,name=username,proto3" json:"username,omitempty"`
Pwad string `protobuf:"bytes,2,opt,name=pwad,proto3" json:"pwad,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *LoginReq) Reset() { *m = LoginReq{} }
func (m *LoginReq) String() string { return proto.CompactTextString(m) }
func (*LoginReq) ProtoMessage() {}
func (*LoginReq) Descriptor() ([]byte, []int) {
return fileDescriptor_08d451189a7398cb, []int{0}
}
func (m *LoginReq) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_LoginReq.Unmarshal(m, b)
}
func (m *LoginReq) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_LoginReq.Marshal(b, m, deterministic)
}
func (m *LoginReq) XXX_Merge(src proto.Message) {
xxx_messageInfo_LoginReq.Merge(m, src)
}
func (m *LoginReq) XXX_Size() int {
return xxx_messageInfo_LoginReq.Size(m)
}
func (m *LoginReq) XXX_DiscardUnknown() {
xxx_messageInfo_LoginReq.DiscardUnknown(m)
}
var xxx_messageInfo_LoginReq proto.InternalMessageInfo
func (m *LoginReq) GetUsername() string {
if m != nil {
return m.Username
}
return ""
}
func (m *LoginReq) GetPwad() string {
if m != nil {
return m.Pwad
}
return ""
}
type LoginRes struct {
Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *LoginRes) Reset() { *m = LoginRes{} }
func (m *LoginRes) String() string { return proto.CompactTextString(m) }
func (*LoginRes) ProtoMessage() {}
func (*LoginRes) Descriptor() ([]byte, []int) {
return fileDescriptor_08d451189a7398cb, []int{1}
}
func (m *LoginRes) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_LoginRes.Unmarshal(m, b)
}
func (m *LoginRes) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_LoginRes.Marshal(b, m, deterministic)
}
func (m *LoginRes) XXX_Merge(src proto.Message) {
xxx_messageInfo_LoginRes.Merge(m, src)
}
func (m *LoginRes) XXX_Size() int {
return xxx_messageInfo_LoginRes.Size(m)
}
func (m *LoginRes) XXX_DiscardUnknown() {
xxx_messageInfo_LoginRes.DiscardUnknown(m)
}
var xxx_messageInfo_LoginRes proto.InternalMessageInfo
func (m *LoginRes) GetToken() string {
if m != nil {
return m.Token
}
return ""
}
type RegDetails struct {
Username string `protobuf:"bytes,1,opt,name=username,proto3" json:"username,omitempty"`
Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"`
Usertype string `protobuf:"bytes,3,opt,name=usertype,proto3" json:"usertype,omitempty"`
Company string `protobuf:"bytes,4,opt,name=company,proto3" json:"company,omitempty"`
Email string `protobuf:"bytes,5,opt,name=email,proto3" json:"email,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *RegDetails) Reset() { *m = RegDetails{} }
func (m *RegDetails) String() string { return proto.CompactTextString(m) }
func (*RegDetails) ProtoMessage() {}
func (*RegDetails) Descriptor() ([]byte, []int) {
return fileDescriptor_08d451189a7398cb, []int{2}
}
func (m *RegDetails) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_RegDetails.Unmarshal(m, b)
}
func (m *RegDetails) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_RegDetails.Marshal(b, m, deterministic)
}
func (m *RegDetails) XXX_Merge(src proto.Message) {
xxx_messageInfo_RegDetails.Merge(m, src)
}
func (m *RegDetails) XXX_Size() int {
return xxx_messageInfo_RegDetails.Size(m)
}
func (m *RegDetails) XXX_DiscardUnknown() {
xxx_messageInfo_RegDetails.DiscardUnknown(m)
}
var xxx_messageInfo_RegDetails proto.InternalMessageInfo
func (m *RegDetails) GetUsername() string {
if m != nil {
return m.Username
}
return ""
}
func (m *RegDetails) GetPassword() string {
if m != nil {
return m.Password
}
return ""
}
func (m *RegDetails) GetUsertype() string {
if m != nil {
return m.Usertype
}
return ""
}
func (m *RegDetails) GetCompany() string {
if m != nil {
return m.Company
}
return ""
}
func (m *RegDetails) GetEmail() string {
if m != nil {
return m.Email
}
return ""
}
func init() {
proto.RegisterType((*LoginReq)(nil), "userPB.loginReq")
proto.RegisterType((*LoginRes)(nil), "userPB.loginRes")
proto.RegisterType((*RegDetails)(nil), "userPB.regDetails")
}
func init() { proto.RegisterFile("userPB.proto", fileDescriptor_08d451189a7398cb) }
var fileDescriptor_08d451189a7398cb = []byte{
// 231 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x90, 0x31, 0x4f, 0x85, 0x30,
0x14, 0x85, 0x83, 0x3e, 0x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 0x1a, 0x31, 0xce,
0xb6, 0x74, 0xff, 0xff, 0xbf, 0x66, 0xa1, 0xeb, 0xfb, 0xdf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x69,
0x84, 0xa0, 0xd2, 0x7b, 0x01, 0x00, 0x00,
}
// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConnInterface
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion6
// AuthServiceClient is the client API for AuthService service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type AuthServiceClient interface {
Login(ctx context.Context, in *LoginReq, opts ...grpc.CallOption) (*LoginRes, error)
Signup(ctx context.Context, in *RegDetails, opts ...grpc.CallOption) (*LoginRes, error)
}
type authServiceClient struct {
cc grpc.ClientConnInterface
}
func NewAuthServiceClient(cc grpc.ClientConnInterface) AuthServiceClient {
return &authServiceClient{cc}
}
func (c *authServiceClient) Login(ctx context.Context, in *LoginReq, opts ...grpc.CallOption) (*LoginRes, error) {
out := new(LoginRes)
err := c.cc.Invoke(ctx, "/userPB.authService/Login", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *authServiceClient) Signup(ctx context.Context, in *RegDetails, opts ...grpc.CallOption) (*LoginRes, error) {
out := new(LoginRes)
err := c.cc.Invoke(ctx, "/userPB.authService/Signup", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// AuthServiceServer is the server API for AuthService service.
type AuthServiceServer interface {
Login(context.Context, *LoginReq) (*LoginRes, error)
Signup(context.Context, *RegDetails) (*LoginRes, error)
}
// UnimplementedAuthServiceServer can be embedded to have forward compatible implementations.
type UnimplementedAuthServiceServer struct {
}
func (*UnimplementedAuthServiceServer) Login(ctx context.Context, req *LoginReq) (*LoginRes, error) {
return nil, status.Errorf(codes.Unimplemented, "method Login not implemented")
}
func (*UnimplementedAuthServiceServer) Signup(ctx context.Context, req *RegDetails) (*LoginRes, error) {
return nil, status.Errorf(codes.Unimplemented, "method Signup not implemented")
}
func RegisterAuthServiceServer(s *grpc.Server, srv AuthServiceServer) {
s.RegisterService(&_AuthService_serviceDesc, srv)
}
func _AuthService_Login_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(LoginReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AuthServiceServer).Login(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/userPB.authService/Login",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AuthServiceServer).Login(ctx, req.(*LoginReq))
}
return interceptor(ctx, in, info, handler)
}
func _AuthService_Signup_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(RegDetails)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(AuthServiceServer).Signup(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: "/userPB.authService/Signup",
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(AuthServiceServer).Signup(ctx, req.(*RegDetails))
}
return interceptor(ctx, in, info, handler)
}
var _AuthService_serviceDesc = grpc.ServiceDesc{
ServiceName: "userPB.authService",
HandlerType: (*AuthServiceServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Login",
Handler: _AuthService_Login_Handler,
},
{
MethodName: "Signup",
Handler: _AuthService_Signup_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "userPB.proto",
}
+22
View File
@@ -0,0 +1,22 @@
//protoc -I userPB/ userPB/userPB.proto --go_out=plugins=grpc:userPB
syntax = "proto3";
package userPB;
message loginReq{
string username = 1;
string pwad = 2;
}
message loginRes{
string token = 1;
}
message regDetails{
string username = 1;
string password = 2;
string usertype = 3;
string company = 4;
string email =5;
}
service authService{
rpc Login(loginReq) returns (loginRes);
rpc Signup(regDetails) returns (loginRes);
}