Monday 1 May 2017

Error: Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup

I am currently implementing a google login and google calender implementation and testing out a function when a google user logs in it pulls their events and prints to the console. however, I am getting the following error in the console: Error: Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup. and when I console.log the calendar, it gives me a null.

I have made sure google+ API and google calendar api are both enabled in the console as well.

I am new to web development in general, I followed a tutorial to get me started and began trying to use the google api's. I am using the MEAN stack for this project. Here is the relevant code (I think) If there is other code you need to see let me know and ill upload it. Thanks for the help in advance.

    var FacebookStrategy = require('passport-facebook').Strategy;
var User = require('../models/user');
var session = require('express-session');
var jwt = require('jsonwebtoken');
var secret = 'check123';
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var gcal = require('google-calendar');
var google = require('googleapis');


module.exports = function(app,passport, auth) {


    app.use(passport.initialize());
    app.use(passport.session());
    app.use(session({
        secret: 'keyboard cat',
        resave: false,
        saveUninitialized: true,
        cookie: { secure: false }
    }));

    passport.serializeUser(function(user, done) {
        token = jwt.sign({ username: user.username, email: user.email }, secret, {expiresIn: '24h'});
        done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });

    passport.use(new FacebookStrategy({
            clientID: '422080801499546',
            clientSecret: '34f91021248106dea49daa111bb7ff89',
            callbackURL: "http://localhost:8000/auth/facebook/callback",
            profileFields: ['id', 'displayName', 'photos', 'email']
        },
        function(accessToken, refreshToken, profile, done) {
            console.log(profile._json.email);
            User.findOne({ email: profile._json.email }).select('username password email').exec(function(err, user){
                if(err) done(err);

                if (user && user !== null) {
                    done(null, user);
                } else {
                    done(err);
                }
            });
            //done(null, profile);
        }
    ));



// Use the GoogleStrategy within Passport.
//   Strategies in Passport require a `verify` function, which accept
//   credentials (in this case, an accessToken, refreshToken, and Google
//   profile), and invoke a callback with a user object.
    passport.use(new GoogleStrategy({
            clientID: '655984940226-ob15jvq3hvqha4969tlb3oco9tun1i9t.apps.googleusercontent.com',
            clientSecret: 'hsZtBDsfiCvdPz0gT-tqdUZ_',
            callbackURL: "https://frozen-woodland-75947.herokuapp.com/auth/google/callback"
        },
        function(accessToken, refreshToken, profile, done) {

            User.findOne({ email: profile.emails[0].value }).select('username password email').exec(function(err, user){
                if(err) done(err);

                if (user && user !== null) {
                    done(null, user);
                } else {
                    done(err);
                }
            });

            var google_calendar = google.calendar('v3');
            console.log('im here');
            google_calendar.events.list({
                auth: auth,
                calendarId: 'primary',
                timeMin: (new Date()).toISOString(),
                singleEvents: true,
                orderBy: 'startTime'
            }, function(err, calendarList){
                console.log(calendarList);
                if(err){
                    console.log('bad list: ' + err);
                    return;
                }
                var events = calendarList.items;
                if(events.length ==0){
                    console.log('No items found');
                } else {
                    console.log('Upcoming events:');
                    console.log('%s -%s', start, event.summary);
                }

            })


        }

Next is my authentication functions, my api.js:

    var User = require('../models/user');
var jwt = require('jsonwebtoken');
var secret = 'check123';

module.exports = function(router){

    //USER REGISTRATION
    router.post('/users', function(req, res){
        var user = new User();
        user.username = req.body.username;
        user.password = req.body.password;
        user.email = req.body.email;
        if(req.body.username == null || req.body.username == ''|| req.body.password == null || req.body.email == null || req.body.password == '' || req.body.email == ''){
            res.json({ success: false, message: 'Ensure username, email, and password were provided'}); //false if the route is null empty etc.
        } else {
            user.save(function(err){
            if(err) {
                res.json({success: false, message: 'Username or email already exists'});
            } else {
                res.json({success: true, message: 'user created!'});
            }
        });

        }
    });

    //USER LOGIN ROUTE
    //http://localhost:port/api/authenticate
    router.post('/authenticate', function(req,res){
        User.findOne({ username: req.body.username }).select('email username password').exec(function(err,user){
            if(err) throw err;

            if(!user){
                res.json({success: false, message: 'Could not authenticate user'});
            } else if (user) {
                if( req.body.password) {
                    var validPassword = user.comparePassword(req.body.password);
                } else {
                    res.json({success: false, message: 'No password Provided'});
                }
                if(!validPassword) {
                    res.json({ success: false, message: ' Could not Authenticate password'});
                } else {
                    var token = jwt.sign({ username: user.username, email: user.email }, secret, {expiresIn: '24h'}); // create json token when they successfully log in with secret encryption and expires in 24 hours
                    res.json({ success: true, message: ' User Authenticated!', token: token}); // respond to user with that token
                }
            }
        });
    });

    router.use(function(req, res, next){
        var token = req.body.token || req.body.query || req.headers['x-access-token'];
        console.log(token);
        if(token) {
            //varify token
            jwt.verify(token,secret,function(err,decoded){
                if(err) {
                    res.json({success: false, message: 'Token invalid'});

                } else {
                    req.decoded = decoded; //decrpyts token - user/email
                    next();
                }
            });
        }else {
            res.json({success: false, message: 'No token provided'});
        }
    });

    router.post('/me', function(req, res) {
        res.send(req.decoded);
    });

    return router;
}

login controllers:

    //controls main index - runs when main page loads

angular.module('mainController', ['authServices'])


    .controller('mainCtrl', function(Auth,$timeout, $location,$rootScope, $window){
        var app = this; // so we can access outside of scoper

        app.loadme = false;

        $rootScope.$on('$routeChangeStart', function() {
            if(Auth.isLoggedIn()) {
                app.isLoggedIn = true;
                Auth.getUser().then(function(data){
                    app.username = data.data.username;
                    app.useremail = data.data.email;
                    app.loadme = true;
                });
            } else {
                app.isLoggedIn = false;
                app.username = '';
                app.loadme = true;

            }
        });

        this.google = function() {
            $window.location = $window.location.protocol + '//' + $window.location.host + '/auth/google';
        };



        this.doLogin = function(loginData) { //when the register button is pressed controller
            app.loading = true;
            app.errorMsg = false;

            Auth.login(app.loginData).then(function(data){
                if(data.data.success){
                    app.loading = false;
                    app.successMsg = data.data.message + '...redirecting';
                    $timeout(function() {
                        $location.path('/about');
                        app.loginData = '';
                        app.successMsg = false;
                    }, 2000);



                } else {
                    app.loading = false;
                    app.errorMsg = data.data.message;


                }
            });
        };
        this.logout = function() {
            Auth.logout();
            $location.path('/logout');
            $timeout(function(){
                $location.path('/');
            }, 2000);
        };
    })



via Syrus Yeung

No comments:

Post a Comment