0

I am trying to run a working Django server on Apache2. I've install and configured an Apache2 server with the following 000-default.conf:

<VirtualHost *:80>
    # The ServerName directive sets the request scheme, hostname and port that
    # the server uses to identify itself. This is used when creating
    # redirection URLs. In the context of virtual hosts, the ServerName
    # specifies what hostname must appear in the request's Host: header to
    # match this virtual host. For the default virtual host (this file) this
    # value is not decisive as it is used as a last resort host regardless.
    # However, you must set it for any further virtual host explicitly.
    #ServerName www.example.com

    ServerAdmin oreo@localhost
    DocumentRoot /var/www/html

    # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
    # error, crit, alert, emerg.
    # It is also possible to configure the loglevel for particular
    # modules, e.g.
    #LogLevel info ssl:warn

    ErrorLog /home/chunao/WhiteBoard/error.log
    CustomLog /home/chunao/WhiteBoard/access.log combined

    # For most configuration files from conf-available/, which are
    # enabled or disabled at a global level, it is possible to
    # include a line for only one particular virtual host. For example the
    # following line enables the CGI configuration for this host only
    # after it has been globally disabled with "a2disconf".
    #Include conf-available/serve-cgi-bin.conf
    
    <Directory /home/chunao/WhiteBoard/Backend/WhiteBoardBackEnd/WhiteBoardBackEnd/>
        <Files wsgi.py>
            Require all granted
        </Files>
    </Directory>

    <Directory /home/chunao/>
        Require all granted
    </Directory>

    <Directory "/var/www/html">
        Options FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    <Directory /home/chunao/WhiteBoard/Backend/WhiteBoardBackEnd/API/>
        Require all granted
    </Directory>

    WSGIDaemonProcess WhiteBoard python-path=/home/chunao/WhiteBoard/Backend/WhiteBoardBackEnd python-home=/home/chunao/WhiteBoard/Backend/WhiteBoardBackEnd/Backend
    WSGIProcessGroup WhiteBoard
    WSGIScriptAlias / /home/chunao/WhiteBoard/Backend/WhiteBoardBackEnd/WhiteBoardBackEnd/wsgi.py
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

It is connected to a Django project named WhiteBoard that is also connected to a local MySQL database. If I use sudo python3 manage.py runserver, everything works fine. If I remove the sudo, it will give me the error of access denied for user root@localhost.

Here is my Setting.py:

import os
from pathlib import Path
from decouple import config

import sys

print (sys.path)

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config("SECRET_KEY")

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = [
                 '172.16.50.73'
                 ]

# Application definition

AUTHENTICATION_BACKENDS = (
    "django.contrib.auth.backends.ModelBackend",
)

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'rest_framework.authtoken',
    'corsheaders',
    'API',
    'crispy_forms',
    'django_extensions',
    'WhiteBoardBackEnd',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ALLOWED_ORIGINS = [
    "http://127.0.0.1:8000",
]

ROOT_URLCONF = 'WhiteBoardBackEnd.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['/API/templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'WhiteBoardBackEnd.wsgi.application'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django_data_base',
        'USER': 'root',
        'PASSWORD': '', #hidden, but I can assure it is correct
        'HOST': 'localhost',
        'PORT': '3306',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'  # 'http://myhost:port/media/'


# NEW Settings

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.TokenAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
    ],
    'COERCE_DECIMAL_TO_STRING': False
}

CORS_ORIGIN_ALLOW_ALL = True

CORS_EXPOSE_HEADERS = ['Content-Type']
DATA_UPLOAD_MAX_MEMORY_SIZE = 99999999999999

My problem is that now I have this apache server setup, It is also giving me this error message: enter image description here but I've already run apache services with sudo systemctl start apache2 and I don't know how to give it higher privilege. I've tried to manually add privilege to the user root@localhost in MySQL but it didn't work. Please, I need help. Thank you!

  • Your database authorization is wrong. You have not set the right grants. – Klaus D. Nov 05 '21 at 10:13
  • @KlausD. OP says it works when using sudo, so my assumption is that within mysql grants are correct for root user. Could it be something at operating system level and use of sudo? - see e.g. [this answer](https://stackoverflow.com/questions/39281594/error-1698-28000-access-denied-for-user-rootlocalhost) – KolaB Nov 05 '21 at 10:26
  • what is the code on line 185 in file connections.py ? – mister_cool_beans Nov 05 '21 at 10:38
  • @MikeMoy it is a connection file of Django and it's not created by me. It is `super().__init__(*args, *kwargs2)` – De Santa Michell Nov 05 '21 at 15:42
  • 1
    @KolaB It could be. I am using AWS ec2 and they might have a different way to handle socket (security thing, perhaps?), but I really don't know why it works on Django native server but not on Apache2 – De Santa Michell Nov 05 '21 at 15:43

1 Answers1

1

So the answer is that root is using socket auth, which somehow Apache is not using. The solution is just to create a new MySQL user with PW authentication, flush the privilege and change the Django setting so that Apache will use that account. Once it's done my Apache can access MySQL normally.